text:
Q: cumsum per group in column ordered by second column append to original dataframe I have a dataframe of 2 columns with multiple groups, in this case, column 1 with groups, and column 2 groups, (in this case dates which must be in correct order).   I want a cumulative summation of the third column per each unique group in col1 ordered by col2.
I have yet to find an elegant method to accomplish this.  The following code will correctly accomplish the task, but sums the whole table, and is very dependent on getting all of the sorts correct.
multidf = df.groupby(by=['col1','col2']).sum().groupby(level=[0]).cumsum()
Will give a hierarchical index solution, but I could not find a way to take the resulting cumulative sum column and attach it to the original dataframe without multistep merge commands.  The reset_index command just converts the table back to its original state.
Looking for a better method to achieve desired output as shown.  I have messed with lambda, apply, aggregrate commands can't quite get anything to work.
In[229]: df#example dataframe
Out[229]:
  col1                 col2  col3
0    a  2013/01/03 00:00:00     1
1    a  2013/03/05 09:43:31     3
2    b  2013/03/07 00:00:00     4
3    b  2013/03/07 00:00:00     2
4    a  2013/03/07 00:00:00     0

import numpy as np
import pandas as pd
##example dataframe
df = pd.DataFrame({'col1' : ['a','a','b','b','a'],
               'col2' : ['2013/01/03 00:00:00', '2013/03/05 09:43:31', '2013/03/07 00:00:00',\
                         '2013/03/07 00:00:00', '2013/03/07 00:00:00'],
               'col3' : [1,3,4,2,0]})
df = df.sort(['col1','col2'])
jj= df.groupby(by = ['col1'],sort=['col1','col2']).cumsum()

df = df.sort(['col1','col2'])

##multi alternative, can't get result back into original df elegantly
multidf = df.groupby(by=['col1','col2']).sum().groupby(level=[0]).cumsum()

df['cumsum'] = jj['col3']
In[227]: df ## result of unelegant method, desired output though how else can i achieve this?
Out[227]:
  col1                 col2  col3 cumsum
0    a  2013/01/03 00:00:00     1      1
1    a  2013/03/05 09:43:31     3      4
4    a  2013/03/07 00:00:00     0      4
2    b  2013/03/07 00:00:00     4      4
3    b  2013/03/07 00:00:00     2      6

A: It would be easier to set the column you want to sort as index. Then use groupby.transform(pd.Series.cumsum). See below:
In [1]: df
Out[1]:
  col1                 col2  col3
0    a  2013/01/03 00:00:00     1
1    a  2013/03/05 09:43:31     3
2    b  2013/03/07 00:00:00     4
3    b  2013/03/07 00:00:00     2
4    a  2013/03/07 00:00:00     0

In [2]: df1=df.set_index('col2').sort_index()
In [3]: df1
Out[3]:
                    col1  col3
col2
2013/01/03 00:00:00    a     1
2013/03/05 09:43:31    a     3
2013/03/07 00:00:00    b     4
2013/03/07 00:00:00    b     2
2013/03/07 00:00:00    a     0

In [4]: df1['cumsum']=df1.groupby('col1')['col3'].transform(pd.Series.cumsum)

In [5]: df1
Out[5]:
                    col1  col3  cumsum
col2
2013/01/03 00:00:00    a     1       1
2013/03/05 09:43:31    a     3       4
2013/03/07 00:00:00    b     4       4
2013/03/07 00:00:00    b     2       6
2013/03/07 00:00:00    a     0       4


text:
Q: BASH - math image size I am trying to find fractions of an image size using this
w=$(identify -format "%w" $1)
h=$(identify -format "%h" $1)
w16=$(($w/16))
w2=$(($w/2))
h16=$(($h/16))
h2=$(($h/2))

which returns this error
identify: unable to open image `1323728291642.jpg': ��� @ error/blob.c/OpenBlob/2489.
identify: unable to open image `1323728291642.jpg':  @ error/blob.c/OpenBlob/2489.
identify: unable to open image `1323728291642.jpg': �8� @ error/blob.c/OpenBlob/2489.
identify: unable to open image `1323728291642.jpg':  @ error/blob.c/OpenBlob/2489.
bash: /16: syntax error: operand expected (error token is "/16")

it was being used in this context
for i in `cat ../list`; do . ~/base64ensize.sh "$i" jpg|gpaste add;read -p "Press [Enter] key to start backup..."; done

list was a list of image files in the current directory
if needed here is the rest of base64ensize.sh
w=$(identify -format "%w" $1)
h=$(identify -format "%h" $1)
w16=$(($w/16))
w2=$(($w/2))
h16=$(($h/16))
h2=$(($h/2))
#echo $w $w2 $w15 $h $h2 $h16
echo -n "" >> temp
sed s/"EXT"/$2/ temp
rm temp

A: for i in `cat list`;
do
   ./base64ensize.sh "$i" jpg |tee >(wc 1>&2 ); # use gpaste add and not wc 1>&2 here
   read -p "Press [Enter] key to start backup...";
done

base64ensize.sh:
w=$(identify -format "%w" $1)
   h=$(identify -format "%h" $1)
   w16=$((w/16))
   w2=$((w/2))
   h16=$((h/16))
   h2=$((h/2))
   #echo $w $w2 $w15 $h $h2 $h16
   echo -n ""
   echo
   #sed s/"EXT"/$2/ temp
   #rm temp

you may want to put the for loop into run.sh and then generte your html by:
bash run.sh > images.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: ABCpdf unicode character as? I am using ABCPDF version 9.1.2.5
our process for creating PDF is like navigate URL in the background and get the full HTML as a string  we are using AddImageHtml() method for creating a PDF, that would work perfectly with the English language but not works for another language like Chinese Japanese which is represented as a "?" mark
Dim PDFData() As Byte = Nothing
Dim HtmlPage As String
Dim PDFDoc As New Doc
PDFDoc.Font = PDFDoc.EmbedFont("Arial Unicode MS", LanguageType.Unicode, False, True)
HtmlPage = myclass.GetWebPageAsString(TargetURL, PostData)
If Orientation = Myclass.PDFOrientation.Landscape Then
 Width = PDFDoc.MediaBox.Width
 Height = PDFDoc.MediaBox.Height
 Left = PDFDoc.MediaBox.Left
 Bottom = PDFDoc.MediaBox.Bottom
 PDFDoc.Transform.Rotate(90, Left, Bottom)
 PDFDoc.Transform.Translate(Width, 0)
 PDFDoc.Rect.Width = Height
 PDFDoc.Rect.Height = Width
End If
PDFDoc.Rect.Inset(20, 20)
PDFDoc.HtmlOptions.Timeout = 3600000
PDFDocID = PDFDoc.AddImageHtml(HtmlPage)
PDFData = PDFDoc.GetData
PDFDoc.Clear()

A: The version of ABCpdf that you are using was discontinued early in 2015. The rendering of CJK characters for the default engine you are using is dependent on the version of Internet Explorer installed on the machine where you are running your application. From version 11, it is now possible to use the Chrome engine which is much less dependent on your operating system configuration. It is also faster and very much more standards compliant.


text:
Q: Android: AsyncTask, my 1st task has not finished when the other starts Here's my code in my main thread
            myAsyncRunnable mar = new myAsyncRunnable(GameActivity.this);
            mar.execute("fire");
            PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
            photoTask.execute(null);

in myAsyncRunnable.fire() I have a loop that changes 10 times the image of an ImageView in gameActivity. I want the photoTask to start when the last image has been changed
@Override
protected Void doInBackground(String... params) {
fire();
return null;
}

public void fire() {
        final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
        final int drawables[] = new int[] {R.drawable.fire1,R.drawable.fire2,R.drawable.fire3,R.drawable.fire4,R.drawable.fire5,R.drawable.fire6,R.drawable.fire7,R.drawable.fire8,R.drawable.fire9,R.drawable.fire10,R.drawable.fire11,R.drawable.fire12,R.drawable.fire13,R.drawable.fire14,R.drawable.fire15,R.drawable.fire16};
        for (int i=0;i<drawables.length;i++) {
            final int j=i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    image3.setImageResource(drawables[j]);
                }
            };
            gameactivity.handler.postDelayed(runnable, 200*j);
        }
    }

But photoTask executes before the last image has apperaed. This is probably due to the postDelayed method and I have tried to execute photoTask in the method onPostExecute() but it didn't work either

A: Put photoTask.execute(null); in the onPostExecute() of the first AsyncTask

A: Just as pvn said, you need to override the onPostExecute method too and execute your photo async class there. Put this after the doInBackground method.
@Override
protected void onPostExecute(YourParam param)
{
     PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
        photoTask.execute(null);
}


text:
Q: How to tell Typescript compiler to compile JSX in .ts files? I have some .ts files that has .jsx syntax in them. I want to tell tsc to compile my these .ts files like compiling .tsx files.
Is is possible to configure tsc to do that?
How can I configure vscode to support syntax highlighting for JSX syntax in these files?

A: No, you must have your react code in .tsx files, as the docs say:

In order to use JSX you must do two things.

*

*Name your files with a .tsx extension

*Enable the jsx option

The reason for this is that in typescript you cast in this form:
interface Point {
    x: number;
    y: number;
}

let p = <Point> {};

In tsx files however this is not possible because <Point> can be markup for a Point component.
Because of that in tsx files casting is not possible and you need to type assert:
let p = {} as Point;

But regular .ts files still support the casting form which will cause conflicts if you'll have jsx code in them.


text:
Q: Finding orthonormal basis. Is there error on textbook? The problem is finding orthonormal basis for W=span{u1=x,u2=x^2}
And as lots of people think, it is not very difficult problem
My answer is
${ \sqrt{3}x,\sqrt{80}(x^2-\frac{3}{4}x) }$
But, textbook says
$ \sqrt{3}x,\sqrt{30}(x^2-\frac{1}{2}x)$
I checked another edition of the textbook but it was same.
I use elementary linear algebra by koleman
Is there any error I have made? Because of this problem I can't believe my answer for similar problems.

A: The book's answer isn't orthogonal:   $(x,x^2-\frac12x)=\int_0^1x(x^2-\frac12x)\operatorname dx=[x^4/4-x^3/6]_0^1\neq0$.
Yours, on the other hand,  appears to be correct.


text:
Q: ng-switch-when - does not clear the selection issue: ng-switch-when does not remove the previous data when switching using the options
I have put together the sample.
http://jsfiddle.net/abuhamzah/98q775jL/3/
select "Cash" and enter some number then
select "Check" and enter some number and if you go back to Cash you will still see the previous numbers.
my question is: how can I clear the selection once the user choose the different option?

A: It appears that you have two different values in your model. One for the cheque and one for the cash. Is that what you want? If you just want to use the ng-when to switch the label then you can take the input out of the switch and just have the one value in the model.

        Cash :

        Check #:

   <input type="number" class="form-control" ng-model="payment.amount_tendered" />

So the value payment.amount_tendered is the only value that you end up with. Otherwise, if both values are needed then you may have to write a function that clears the value for you and bind it to the change event of the select.


text:
Q: BufferedReader reads nothing and then terminates the program, why is this? I'm writing a program for an assignment wherein I am supplied population data and child poverty rates by each high school in the country and what I am supposed to do is only read certain columns of data and write them into another new text file, and then another program prints out this information. I try to do this by creating a while loop that reads each line of the file (13486 lines), assigns certain indices of each line to their corresponding arrays and array indices as strings, and then moves onto the next while loop wherein these data are printed in new columns. From there, I want to average the values for each state and print them in the second program. However, I'm not even there yet.
import java.io.*;
import java.util.ArrayList;

public class Main
{

public static void main(String[] args)
        throws FileNotFoundException, IOException
{
    String[] states =
    { "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA",
            "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
            "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
            "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
            "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" };
    File censusData = new File(args[0]);
    if (!censusData.exists())
    {
        System.err.print("Census Data not found.");
    }
    else
    {
        System.out.println("This file definitely exists.");
    }
    // Scanner cdr = new Scanner(censusData);
    // cdr.useDelimiter("\n");
    FileReader fr = new FileReader(censusData);
    BufferedReader br = new BufferedReader(fr);

    ArrayList<String> lines = new ArrayList<String>();
    int[] stateCode = new int[13486];
    int[] population = new int[13486];
    int[] childPopulation = new int[13486];
    String line = new String();
    int i = 0;
    while ((line = br.readLine()) != null)
    {
        stateCode[i] = Integer.parseInt(line.substring(0, 1));
        population[i] = Integer.parseInt(line.substring(82, 89));
        childPopulation[i] = Integer.parseInt(line.substring(91, 98));
        i++;

    }
    br.close();
    File cD = new File(args[1], "newCensusData.txt");
    PrintWriter pw = new PrintWriter(cD);
    i = 0;
    while (childPopulation.length < Integer.parseInt(args[2]))
    {
        pw.printf("%4s", stateCode[i], population[i], childPopulation[i]);
        i++;

    }
    pw.close();

}
}

args[0] is the full path for the file of census information, args[1] is the output directory, and args[2] is the number of entries in the input text file.
What is happening instead is, according to the debugger, the first while loop runs twice and then the program terminates and I don't know why. The file location, output location, everything else is good. newCensusData.txt is even generated but there is no information in there. Can anyone tell me why the BufferedReader object isn't actually reading the lines of the text file?
Edit: I don't think that this has much to do where where I chose to close the different reader/writer objects. Even if I do not close either of them, the result is the same.

A: You are closing the BufferedReader (And PrintWriter) inside the loop, and according to the docs:

Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException.

Change your loop to:
while ((line = br.readLine()) != null)
{

    stateCode[i] = Integer.parseInt(line.substring(0, 1));
    population[i] = Integer.parseInt(line.substring(82, 89));
    childPopulation[i] = Integer.parseInt(line.substring(91, 98));
    i++;
}
br.close();

A: You can open up your BufferedReader with try-with-resources. That way you don't have to worry about explicitly closing your Reader as the statement will take care of it.
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
    String line;
    while ((line = br.readLine()) != null) {
        stateCode[i] = Integer.parseInt(line.substring(0, 1));
        population[i] = Integer.parseInt(line.substring(82, 89));
        childPopulation[i] = Integer.parseInt(line.substring(91, 98));
        i++;
    }
} catch (FileNotFoundException ex) {
    //Catch your exception
} catch (IOException ex) {
    //Catch your exception
}

From the documentation:

The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).


text:
Q: Split a string into unicode words? (particularly Vietnamese) I have been trying to split a string that contains text in Vietnamese into individual words. For example:

s = "Chào bạn, mình tên Đạt."

Will be splitted into an array:

arr = {"Chào", "bạn", "mình", "tên", "Đạt"}

Normally in English, this would be easily solve by 1 line only:
arr = s.split("\\W+");

but since there are many non-alphabetic letters in Vietnamese, it can't be solve by just one line. So the question is: Is there any regular expressions that can replace this "\W+" (I'm not very good with regular expressions)? If not, is there any other ways around it?

A: Split a String by space and punctuation. You can add your punctuation. As some of the characters in regex are reserved, I prefer to use them a in a character class [].
arr = s.split("([ ]|[.]|[,]|[:]|[?])+"); //You can customize punctuation.

This is a working example.
public static void main(String[] args) {
   String  inputStr = "Chào bạn, mình tên Đạt.";
   String [] splitArray = inputStr.split("([ ]|[.]|[,]|[:]|[?])+");
   for (String s : splitArray) {
       System.out.println(s);
   }
}

Prints:
Chào
bạn
mình
tên
Đạt

Update
In case of simple space character [ ], it works well. However, for this String.
 String  inputStr = "Chào  bạn,\n mình tên\t Đạt.";

Result
Chào
bạn

mình
tên
Đạt

To fix it, use space character class - \s.
  String [] splitArray = inputStr.split("(\\s|[.]|[,]|[:]|[?])+");

Or loop through the array of Strings, and trim them.


text:
Q: send some props to another component for details: I have a context file that export a theme and a function (theme value and toggleThemeMode function) and in Header.jsx component I wanna use these to change the background by Toggle.jsx component.
I don't know exactly how send some props to Toggle.jsx component to change these values ...
////////////////////////////////// theme.jsx (context) //////////////////////////////////
import { createContext, useContext, useState } from "react";

const DARK = "DARK";

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState({ mode: "LIGHT" });

  const toggleThemeMode = () => {
    setTheme(theme.mode === DARK ? "LIGHT" : DARK);
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleThemeMode }}>
      {children}
    </ThemeContext.Provider>
  );
};

const useTheme = () => useContext(ThemeContext);

export { ThemeProvider, useTheme, DARK };

////////////////////////////////// Header.jsx //////////////////////////////////
import React from "react";
import { DARK, useTheme } from "../../contexts/theme";
import { Toggle } from "./toggle";

import logo from "../../assets/images/logo.svg";
import profilePicture from "../../assets/images/profile.jpg";

const Header = () => {

  const { theme, toggleThemeMode } = useTheme();

  const showMobileMenu = () => {
    document.getElementById("main-wrapper").classList.toggle("show-sidebar");
  };

  const onToggleChange = () => toggleThemeMode();

  const isDark = theme.mode === DARK;

  return (

      <nav className={`navbar navbar-${isDark ? "dark" : "light"} h-100`}>

          <button
            className="btn-link nav-toggler d-block d-md-none"
            onClick={() => showMobileMenu()}
          >

          </button>

        <Toggle onChange={onToggleChange} />

  );
};

export default Header;

////////////////////////////////// toggle.jsx ///////////////////////////////////////
import PropTypes from "prop-types";

const Toggle = ({ checked, onChange, label = "" }) => {

    const handleChange = (event) => {
        onChange?.(event);
    };

    return (

            <input
                className="form-check-input"
                type="checkbox"
                id="flexSwitchCheckDefault"
                checked={checked}
                onChange={handleChange}
            />

                {label}

    );
};

Toggle.propTypes = {
    checked: PropTypes.bool.isRequired,
    onChange: PropTypes.func,
    label: PropTypes.string,
};

export { Toggle };

A: inside Toggle component, just use the states from the context


text:
Q: dynamic and snapshot views in clearcase I have been using clearcase snapshot views in my current project. so, it requires update to refresh content. does it mean any update I do on view is updated to the servers and any updates others do are updated to my view? . Also, If I  try to checkout a file in snapshot view which somebody else  has already checked out in his snapshot view  but not updated, will I succeed?

A:
does it mean any update I do on view is updated to the servers?

Only if you do a cleartool checkin (commit the new version of the files you were working on after a checkout)

and any updates others do are updated to my view?

Only if you do a cleartool update (a refresh of your snpashot view)

If I try to checkout a file in snapshot view which somebody else has already checked out in his snapshot view but not updated, will I succeed?

You will if the other checkout was unreserved.
If it was a checkout reserved, you won't be able to checkout (but you will be able to hijack the file)
See:

*

*"What is the difference between a reserved checkout and an unreserved checkout?"

*"Identifying hijacked files in a snapshot view"

Hijacking an element in a snapshot view involves making it writable and making a change to it.


text:
Q: DateTime Comparison in Oracle I am doing comparison between several dates in my stored procedure.
    TODAY := TO_DATE(TO_CHAR(SYSDATE, 'DD-MON-YYYY') ||
             ' 09:00:00', 'DD-MON-YYYY HH24:MI:SS');

    IF PREVIOUS_DATE < TODAY AND
       TO_DATE(CURRENT_DATE, 'DD-MON-YYYY HH24:MI:SS') >= TODAY THEN
        -- do something
    ELSE
        -- do something else

When I set CURRENT_DATE = SYSDATE, it did not get into the IF part. Can someone tell me where did i do wrong?

A:
"CURRENT_DATE is of type VARCHAR2 "

Well that scuppers my first idea 8-)
But I think the problem is in your use of CURRENT_DATE.  Assuming that is the Oracle function there are two potential problems:

*

*CURRENT_DATE is a DATE datatype and so has a time element.  There's no point in casting it to a date.

*CURRENT_DATE returns a value adjusted for the system timezone.  Which is presumably the point of your IF test.  But do you know what the values are?

But it remains a straightforward debugging task.  Check your values to understand what's happening.  Here is an example using DBMS_OUTPUT (AKA The Devil's Debugger) because I don't know if you're working in an environment with better tools.
TODAY := trunc(sysdate) + 9/24;

dbms_output.put_line('TODAY = '||to_char(today, 'DD-MON-YYYY HH24:MI:SS'));
dbms_output.put_line('PREVIOUS_DATE = '||to_char(previous_date, 'DD-MON-YYYY HH24:MI:SS'));
dbms_output.put_line('CURRENT_DATE = '||current_date);

IF PREVIOUS_DATE < TODAY AND
   to_date(CURRENT_DATE, 'DD-MON-YYYY HH24:MI:SS') >= TODAY
THEN
    ....

Might as well simplify your code at the same time.
Remember, to see output from DBMS_OUTPUT.PUT_LINE you need to SET SERVEROUTPUT ON for whatever client you're using.

Incidentally, it is bad practice to declare variables which share the same name as Oracle built-ins.  This is why it is a good idea to add a scoping prefix (l_ for local, p_ for parameter, etc) to our declarations.  We don't have to do the full Hungarian to get a lot of benefit.


text:
Q: Android: How to check if TextView is bold or italic programatically I would like to know how to construct an if statement to check if a TextView is bold or italic. Please help. Thank you.

A: Try
textView.getTypeface()

then check if it is equal to

*

*Typeface.BOLD

*Typeface.ITALIC

*Typeface.BOLD_ITALIC

A: To check if textview is BOLD and ITALIC, use following code:
 if((textView.getTypeface().getStyle() & Typeface.BOLD)!=0 &&(textView.getTypeface().getStyle() & Typeface.ITALIC)!=0){
                  //do your stuff

}
To check if textview is either BOLD or ITALIC, use following code:
 if((textView.getTypeface().getStyle() & Typeface.BOLD)!=0 ||(textView.getTypeface().getStyle() & Typeface.ITALIC)!=0){
                      //do your stuff
}

A: http://developer.android.com/reference/android/widget/TextView.html#getTypeface()
public Typeface getTypeface ()

returns:

the current typeface and style in which the text is being displayed.

if(yourTextViewInstance.getTypeface()!=null){
   if(yourTextViewInstance.getTypeface().getStyle()==Typeface.BOLD || yourTextViewInstance.getTypeface().getStyle()==Typeface.ITALIC){
      //do your stuff
   }
}


text:
Q: How to get this recursive function in scheme to return true My function element? is supposed to take a set S (a list whose order doesn't matter) and an element e and then returns #t if the element is in the set, or #f if the element is not in the set. All of my test cases work, except for this one:
(element? '("a" "b" "c") "ab")
It seems to not return anything, but I have no clue why. I went through the debugger to try and figure it out, but I can't figure it out because it just exits the function without returning anything. The following is my code:
(define (element? S e)

  (cond [(null? S) #F]
        [(equal? (car S) e) #T]
        [(element? (cdr S) e)]
        ))

Any thoughts? I must be missing something fundamental here.

A: Change the last cond clause to use else as the condition.
(define (element? S e)

  (cond [(null? S) #F]
        [(equal? (car S) e) #T]
        [else (element? (cdr S) e)]
        ))

When a clause consists just of a condition, the value of the condition is returned if it's not #f. If it's #f, cond continues with the following tests. In this case, there are no remaining tests, so it returns nothing (the language specification says the result is undefined). Use else as the last condition to ensure that you return the value of the recursive call whatever it is.
So your code returns #t when the recursion returns #t, but doesn't return anything when it returns #f.


text:
Q: How to create a function based on CAST Due to some reasons, I want to create a function based on cast function.
It's just a wrap of cast.
CREATE OR REPLACE FUNCTION convert(in1 anyelement, in2 anyelement)
RETURNS anyelement AS $func$
BEGIN
    execute $$ SELECT CAST(in2 AS in1) $$;
END
$func$
LANGUAGE plpgsql;

But when I executed the function, I got the error like the following:
select convert(float, 1);

ERROR:  column "float" does not exist
LINE 1: select convert(float, 1);
===============================================

How can I make the my custom function works


text:
Q: Strange behaviour on dividing -ve int/-ve int ,in java Although I am not new to java, I observed this peculiar behavior the other day. I was refreshing my basics by running code consisting of basic arithmetic operations. Now according to java (and basic rules of arithmetic's ofcourse) , -ve * -ve OR -ve / -ve is a +ve number.
But compiling this source:-
int b = Integer.MIN_VALUE / -1;
System.out.println("b:  " + b);

Gives me output:-

b:  -2147483648

Which is -ve, Can anyone point me whats wrong? I know it must be small thing that I cant notice.

A: You have an overflow. Per java specification, the sign is not guaranteed in overflow.
The overflow is due to the fact that
Integer.MIN_VALUE = -2147483648;
Integer.MAX_VALUE = 2147483647;

so -2147483648*(-1) is 2147483648, which is over the max value.

A: To divide by -1 is the same as negating the number.
Since the range of integers (-2147483648 to 2147483647) is 1 larger in magnitude on the negative side -Integer.MIN_VALUE equals Integer.MAX_VALUE+1 which overflows back to Integer.MIN_VALUE.
System.out.println(Integer.MIN_VALUE == -Integer.MIN_VALUE); // prints 'true'


text:
Q: Get all the users within radius from MySQL with Spatial Point I have a MySQL table on my local server. The table includes latitude, longitude and POINT(latitude, longitude) for each user. I am trying to get all the id user within 10 kilometres from center.
I would like not to use latitude and longitude but only the Point. But I don't know how to do it. I also heard about SRID to modify in the POINT but I did not quite understand
Here is my table for the moment
#   Name        Type
1   lat         decimal(10,8)
2   lng         decimal(11,8)
3   latlng      point
4   id_user     int(10)

Indexes
Keyname Type    Unique  Packed  Column  Cardinality Collation   Null    Comment
latlng  SPATIAL No      No      latlng (32)     A   No

How could I do that in PHP?
Just for information, what is the best thing between using a Point and latitude/longitude?

A: I am a postgres/postgis user, but they have equivalents.  If you have the ability to add columns to your table you should convert the lat/lons to Point() objects maybe using something like ST_PointFromText and then you can compare them to each other using ST_Distance()
Ref: https://dev.mysql.com/doc/refman/8.0/en/gis-data-formats.html
Edit: apparently mySql does not have the more efficient ST_DWithin() (See: Whats the equivalent of ST_DWithin (PostGIS - PostgreSQL) for MySQL?) so you probably stuck with ST_Distance().
SRID 4326 is a common one for these types of lat/lon coordinate systems.
Ref: https://desktop.arcgis.com/en/arcmap/10.3/manage-data/using-sql-with-gdbs/what-is-an-srid.htm


text:
Q: Why it got extremely slow? I've been working on RoR apps using RubyMine in Ubuntu within a Virtual Machine in Windows 7
Well .. every thing went fine for a long time ..
But newly, I've been noticing that editing any file would take very long time ( over 15 seconds )
Just when I try to type any thing .. it will hang for too long seconds ..
Any idea ? what could be wrong ? how can I reset RubyMine ?
EDIT
Ubuntu works fine inside vm, I can do other tasks with no delay, so VM process is not hanged, what hangs when I try to edit a file inside RubyMine is RubyMine it self.
Thanks

A: What I did is re-install RubyMine on a different location, and every thing is fine again ..


text:
Q: How to subclass QVector? I have a class named Symbol and I would like to create a QVector subclass (Symbols) to add some useful methods. But when I use Symbols from another class A, the compiler gives the error 'Symbols does not name a type'.
class Symbols: public QVector< Symbol >
{
public:
    Symbols() {}

    // Useful methods
    QSymbol findSymbol(const QString &name);

    // ...
};

class A
{
private:
    Symbols symbols;
};

Is it correctly subclassed?
Why appears 'Symbols does not name a type' when compiles class A?

A: It's usually ill advised to derive from a container. You almost always want a "Has A" relationship otherwise your class will expose members that users of your class can use which may corrupt the state.
Also it looks like you're trying to implement a look up in your class which means perhaps QMap  or QHash would be a more appropriate container

A: After these comments, I must add this to the answer. Don't inherit from QVector<T>. That type doesn't have virtual destructor, and the most important thing in the inheritance (IS-A) relationship will be broken in that case.
Look into your class Symbols, and imagine you've over time increased complexity of it, so now you have destructor and constructor somewhere:
class Symbols: public QVector<Symbol>
{
    ~Symbols()
    {
        important_cleanup_here();
    }
};

You might think that Symbols is a subtype of QVector<Symbol>, so one of your clients write something like this:
QVector<Symbol>* symbols = new Symbols();

Sound good, right? After all, Symbols extends QVector<Symbol>, so it can follow substitute principle, right? Wrong. Because QVector<T> destructor is not virtual, this will not call Symbols destructor!
delete symbols;

Worse than that, this is undefined behavior and compiler could do whatever he feels like.
If you just want convenient method, create a non-method which will do the trick for you
QSymbol findSymbol(const QVector<QSymbol>&, const QString& name);

(for the reference on this, read this amazing Scott Meyer's article: http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197)
In your example, of course, there's nothing to be scared of. But why putting such a burden on one of your classes, when you can use composition without any fear?
Also, refer to this (and few others) reported bug on this: https://bugreports.qt.io/browse/QTBUG-8292
Other than all other problems, I can see one right here:
class Symbols: public QVector<Symbol>
{
      QSymbol findSymbol(const QString &name);
};

Based on what I see, it should be either
class Symbols: public QVector<Symbol>
{
      Symbol findSymbol(const QString &name);
};

or
class Symbols: public QVector<QSymbol>
{
      QSymbol findSymbol(const QString &name);
};

A: I found it!
The problem was that I had a circular dependence.
Class Symbols:
#ifndef SYMBOLS_H
#define SYMBOLS_H
#include <QVector>
#include "A.h"
#include "symbol.h"

class Symbols: public QVector<Symbol>
{
public:
    Symbols() {}
};
#endif // SYMBOLS_H

Class A:
#include "symbols.h"
class A {
   private:
     QSymbols symbols;
}

The #include "A.h" provokes the error. It was there because I had a function with a reference to the class A. I must to search how to resolve circular references :).
Thank you very much to everyone.

A: You are having a couple of issues why your code does not compile:

*

*Missing the semi-colons after the class declarations, provided they are in the same file. Failing that, you would of course need to include the header file containing the Symbol's declaration into your file using it.

*You are using QSymbol return value instead of Symbol.

*You are not including QVector.
Here is a compiling code.
main.cpp
#include <QVector>

class Symbol
{
};

class Symbols: public QVector<Symbol>
{
    public:
      Symbols() {}

      Symbol findSymbol(const QString &name) {}
};

class A {
       Symbols symbols;
};

int main()
{
    return 0;
}

main.pro
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build
qmake && (n)make

That being said, QSymbol looks fishy, too, as there is no such a class in Qt, and you really should not take names like that since that only causes confusion. Also, starting all the classes with a prefix is just silly, and only around in Qt for compatibility reasons, not because it is better than namespaces.
Also, please do not buy the argument that it is ultimately a bad idea to subclass containers. QStringList is a good example to prove that claim wrong.


text:
Q: Client side Facebook "like gate" without https I'm trying to set up a "like gate" where a user has to like a page before seeing certain content on a website (not on Facebook itself). I've found some great resources on SO an elsewhere on how to do it, but I'm running into an issue with http vs. https. My site is not loaded over https, but the Facebook login popup is. The error:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://yoursite.com" from accessing a frame with origin "http://static.ak.facebook.com". The frame being accessed set "document.domain" to "facebook.com", but the frame requesting access did not. Both must set "document.domain" to the same value to allow access.
I'm currently using the code here: https://github.com/vavrecan/facebook-fangate, but have also found this answer useful.
How can I show a user content only if they've liked a specific Facebook page, without using https?

A: Like-gating is discouraged via Platform Policies, and Like-gates via SignedRequests will stop working on November 6th 2014. Have a look at my answer at
How to check if people liked my Facebook FanPage
The error itself is about CORS and not HTTP vs. HTTPS imho.


text:
Q: How can I recover tethering conection after ubuntu-drivers autoinstall in Ubuntu 20.04 I'll try to make the story short.
My Blender was crashing my entire system when I was trying to manipulate materiales and I read the solution was to make a driver upgrade so I performed

sudo ubuntu-drivers autoinstall

And rebooted.
The good news are Blender is working perfectly now.
The bad news are I'm now unable to usb tethering conect and I can't access the Internet.
The computer still reconize my HUAWEI P30 and ask me what I want to do (tranfer photos, files or just charge) and I can activate the usb tethering on settings in my Phone. It even looks like it is connected from my Phone, but no signals of conection on the computer, which is offline.
Can someone please help me to understand and overtake this issue?
Really appreciated.
Felipe


text:
Q: Using sed to modify filenames Since I don't have rename, I would like to use sed to modify 192 file names. Specifically, I want to remove the last 5 characters before the file extension; the first character is an _ and the other 4 are random alphanumeric strings with letters in small or large caps. Example of filenames now:
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_mimus_CMF_0110_S42_L005_R1_001_prinseq_good_30Nd.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_mimus_CMF_0110_S42_L005_R2_001_prinseq_good_GyUj.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_suturellus_CMF_0305_S71_L005_R1_001_prinseq_good_M99E.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_suturellus_CMF_0305_S71_L005_R2_001_prinseq_good_HZrr.fastq
Rhopalidae_Rhopalinae_Harmostini_Harmostes_sp_CMF_0401_S87_L005_R1_001_prinseq_good_96CG.fastq
Rhopalidae_Rhopalinae_Harmostini_Harmostes_sp_CMF_0401_S87_L005_R2_001_prinseq_good_stNk.fastq

What I'd like to do with a sed script:
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_mimus_CMF_0110_S42_L005_R1_001_prinseq_good.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_mimus_CMF_0110_S42_L005_R2_001_prinseq_good.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_suturellus_CMF_0305_S71_L005_R1_001_prinseq_good.fastq
Pyrrhocoridae_Pyrrhocorinae_Pyrrhocorini_Dysdercus_suturellus_CMF_0305_S71_L005_R2_001_prinseq_good.fastq
Rhopalidae_Rhopalinae_Harmostini_Harmostes_sp_CMF_0401_S87_L005_R1_001_prinseq_good.fastq
Rhopalidae_Rhopalinae_Harmostini_Harmostes_sp_CMF_0401_S87_L005_R2_001_prinseq_good.fastq

I've tried sed -r 's/good_(.)+.fastq/good.fastq/' but nothing seems to happen.

A: If you're on a mac, see here for the available commands:
https://ss64.com/osx/
If you search this page for rename, mv comes up as a way to move or rename files.
It's not the same as Windows, it's more like Linux at the command line, which means that there is a lot more you can do with it.

A: Your sed expression
sed -r 's/good_(.)+.fastq/good.fastq/'

works for me. Either it's an error with your invocation, or a difference of your MacOS sed and my Linux-Gnu-sed.
However, since you don't grab the characters, matching (.)+, you don't need braces:
sed -r 's/good_.+.fastq/good.fastq/'

should be sufficient, but could be narrowed down to ...

the first character is an _ and the other 4 are random alphanumeric
  strings with letters in small or large caps.

I pasted your input into a file "files", and tried
sed -r 's/good_(.)+.fastq/good.fastq/' files > files2

pasted your desired output to files3, and a diff didn't showed a difference. What do you get? How do you invoke it?
For moving the file, I guess something like
 for f in *.fastq
 do
     newname=$(echo "$f" | sed ...)
     mv "$f" "$newname"
 done

Maybe it is an invocation error.
update:
When I enable --posix style, I need to replace .+ with .* - maybe that's it.
sed --posix 's/good_.*.fastq/good.fastq/' files

Only worth a hint: The second dot in .*.fastq will match all characters, luckily including the dot itself. Masking it with a backslash would prevent misinterpretation.

A: This is one you don't actually need sed for, just normal bash:
for f in *.fastq; do
    mv "$f" "${f%_*.fastq}.fastq"
done

Should work fine.

A: Seems my mv command was working, but for some reason my finder was not updating.


text:
Q: is there an easy way to find code that is preventing event default? This issue has come up for me a few times:
I write some code that handles an event, for example a click. I click the element and nothing happens. Some other code is calling e.preventDefault() before my code has the chance to handle it.
Question:
Is there a way to find the code that is preventing default that i have overlooked?
I usually solve this by running javascript profiler in firebug and looking at every function that is called during the click (not inside jquery etc) that may be doing the evil. There has to be a better way.

A: I would put a test alert in the function that is supposed to execute, starting at the top and then moving it downwards after each statement. If the alert doesn't execute at the top of the function I would check your HTML element and how you are selecting it. If everything appears to be good, I would search your files using possible element selectors.


text:
Q: Table variable vs temp table in SQL Server 2008
Possible Duplicate:
What's the difference between a temp table and table variable in SQL Server?

What is the difference between table variable and temp table, actually I have two question on it.

*

*how to decide when to use what?

*which one is better in performance and WHY ?

A: The first difference is that transaction logs are not recorded for the table variables. Hence, they are out of scope of the transaction mechanism, as is clearly visible from this example:
create table #T (s varchar(128))
declare @T table (s varchar(128))
insert into #T select 'old value #'
insert into @T select 'old value @'
begin transaction
     update #T set s='new value #'
     update @T set s='new value @'
rollback transaction
select * from #T
select * from @T

Read more : http://www.sql-server-performance.com/articles/per/temp_tables_vs_variables_p1.aspx

A: A table variable is allocated in memory, only when the table gets to large, will it be assigned to the tempdb.
On a temp table you can create indexes as per normal tables, as these are created in the tempdb by definition.
So I would recomend that you make this decision on the number rows to be stored...


text:
Q: Checking whether something is iterable In the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
The for...of construct is described to be able to iterate over "iterable" objects. But is there a good way of deciding whether an object is iterable?
I've tried to find common properties for arrays, iterators and generators, but have been unable to do so.
Aside from doing a for ... of in a try block and checking for type errors, is there a clean way of doing this?

A: For async iterators you should check for the 'Symbol.asyncIterator' instead of 'Symbol.iterator':
async function* doSomething(i) {
    yield 1;
    yield 2;
}

let obj = doSomething();

console.log(typeof obj[Symbol.iterator] === 'function');      // false
console.log(typeof obj[Symbol.asyncIterator] === 'function'); // true

A: If the object has the property Symbol.iterator then it is iterable. Then we can simply check if obj is iterable like this
TypeScript
function isIterable(x: unknown): boolean {
  return !!x?.[Symbol.iterator];
}

Or as an arrow function
const isIterable = (x: unknown): boolean => !!x?.[Symbol.iterator];

JavaScript
const isIterable = x => !!x?.[Symbol.iterator];

Examples
isIterable(["hello", "world"]); // true
isIterable({}); // false
isIterable(null); // false
isIterable(undefined); // false
isIterable(1); // false
isIterable(true); // false
isIterable(Symbol("foo")); // false
isIterable(new Set()); // true
isIterable(new Map()); // true

A: if (Symbol.iterator in Object(value)) {

}

Object will box anything which isn't an object into one. This prevents the in operator from throwing exceptions and removes the need to check for edge cases. null and undefined become empty objects, and the condition evaluates to true for a string, array, Map, Set, and so on.
Alternatively, in an environment that supports optional chaining:
if (value?.[Symbol.iterator]) {

}

The ?. syntax causes null and undefined to be ignored, and property access is safe on all other value types. This might not read like English, but checking the truthiness of a property to assert its existence is fairly idiomatic.
I would personally recommend inlining this code instead of defining a function, as it is relatively short and less ambiguous than a call to some isIterable(x) function.

Keep in mind that the word iterable specifically refers to the iterable protocol, though there exist different ways to loop over objects. The following list is not exhaustive:

*

*arr.forEach(func) runs a function for each element present in an array.

*You can enumerate certain keys of an object with for ... in

*Collections have .keys(), .values() and .entries() methods that return iterators.

*Object.keys(obj), Object.values(obj) or Object.entries(obj) return arrays made from an object's properties, which you can then iterate on.

A: Nowadays, as already stated, to test if obj is iterable just do
obj != null && typeof obj[Symbol.iterator] === 'function'

Historical answer (no more valid)
The for..of construct is part of the ECMASCript 6th edition Language Specification Draft. So it could change before the final version.
In this draft, iterable objects must have the function iterator as a property.
You can the check if an object is iterable like this:
function isIterable(obj){
   if(obj === undefined || obj === null){
      return false;
   }
   return obj.iterator !== undefined;
}

A: Why so verbose?
const isIterable = object =>
  object != null && typeof object[Symbol.iterator] === 'function'

A: The proper way to check for iterability is as follows:
function isIterable(obj) {
  // checks for null and undefined
  if (obj == null) {
    return false;
  }
  return typeof obj[Symbol.iterator] === 'function';
}

Why this works (iterable protocol in depth): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols
Since we are talking about for..of, I assume, we are in ES6 mindset.
Also, don't be surprised that this function returns true if obj is a string, as strings iterate over their characters.

A: 2022 Answer
If you are asking "Is foo iterable" then you probably come from a language (PHP, Python) where that question has a single answer. In modern Javascript, there are different types of iterable. Therefore, you have to check the ability to iterate depending on what you want to do with the variable.
TL;DR

*

*Test the ability to iterate using forEach() with !!foo.forEach, returns true on an Array.

*Test the ability to iterate using for..of with !!foo[Symbol.iterator], returns true on an Array or String.

*Test the ability to iterate using for..in with !!Object.keys(Object(foo)).length, returns true on an Array, String, or Object.

Long answer
Let's define some variables:
const someNumber = 42;
42

const someArray = [1,2,3];
(3) [1, 2, 3]

const someString = "Hello";
"Hello, world!"

const someObject = {a:"A", b:"B"};
{a: "A", b: "B"}

Testing iterability with forEach()
Which types can be iterated with forEach(), tested with !!foo.forEach:
someNumber.forEach(x=>console.log(x));
VM1526:1 Uncaught TypeError: someNumber.forEach is not a function at <anonymous>:1:12

someArray.forEach(x=>console.log(x));
VM916:1 1
VM916:1 2
VM916:1 3
undefined

someString.forEach(x=>console.log(x));
VM957:1 Uncaught TypeError: someString.forEach is not a function at <anonymous>:1:12

someObject.forEach(x=>console.log(x));
VM994:1 Uncaught TypeError: someObject.forEach is not a function at <anonymous>:1:12

Only the Array seems to be iterable with forEach().
Testing iterability with for..of
Which types can be iterated with for..of, tested with !!foo[Symbol.iterator]:
for (x of someNumber) { console.log(x); }
VM21027:1 Uncaught TypeError: someNumber is not iterable at <anonymous>:1:11

for (x of someArray) { console.log(x); }
VM21047:1 1
VM21047:1 2
VM21047:1 3
undefined

for (x of someString) { console.log(x); }
VM21065:1 H
VM21065:1 e
VM21065:1 l
VM21065:1 l
VM21065:1 o
undefined

for (x of someObject) { console.log(x); }
VM21085:1 Uncaught TypeError: someObject is not iterable at <anonymous>:1:11

The Array and String seem to be iterable with for..of, but the Object is not. And both the Number and the Object threw an error.
Testing iterability with for..in
Which types can be iterated with for..in, tested with !!Object.keys(Object(foo)).length:
for (x in someNumber) { console.log(x); }
undefined

for (x in someArray) { console.log(x); }
VM20918:1 0
VM20918:1 1
VM20918:1 2
undefined

for (x in someString) { console.log(x); }
VM20945:1 0
VM20945:1 1
VM20945:1 2
VM20945:1 3
VM20945:1 4
undefined

for (x in someObject) { console.log(x); }
VM20972:1 a
VM20972:1 b
undefined

The Array, String, and Object all seem to be iterable with for..in. And though it did not iterate, the Number did not throw an error.
In modern, ES6 Javascript I see forEach used far more often than for..in or for..of. But Javascript developers must be aware of the differences between the three approaches, and the different behaviour of each approach.

A: As a sidenote, BEWARE about the definition of iterable. If you're coming from other languages you would expect that something you can iterate over with, say, a for loop is iterable. I'm afraid that's not the case here where iterable means something that implements the iteration protocol.
To make things clearer all examples above return false on this object {a: 1, b: 2} because that object does not implement the iteration protocol. So you won't be able to iterate over it with a for...of BUT you still can with a for...in.
So if you want to avoid painful mistakes make your code more specific by renaming your method as shown below:
/**
 * @param variable
 * @returns {boolean}
 */
const hasIterationProtocol = variable =>
    variable !== null && Symbol.iterator in Object(variable);

A: If you wanted to check in fact if a variable is an object ({key: value}) or an array ([value, value]), you could do that:
const isArray = function (a) {
    return Array.isArray(a);
};

const isObject = function (o) {
    return o === Object(o) && !isArray(o) && typeof o !== 'function';
};

function isIterable(variable) {
    return isArray(variable) || isObject(variable);
}

A: I was looking for a check for for ... in and decided on the following.
isIterable (value) {
  // add further checks here based on need.
  return Object.keys(Object(value)).length > 0
}

This will return true for anything that is iterable and has at least one value.
Therefore empty strings, empty arrays, empty objects etc. will return false.
But {a: 'x', b:'y'} will return true.


text:
Q: Is every subgroup of the fundamental group a fundamental group of a covering space? Let $X$ be a path-connected space and $H$ a subgroup of $\pi_1(x,X)$ and let $x\in X$ be a point. Is the following true?
There exists a covering map $\rho:C\rightarrow X$  and $c\in \rho^{-1}(x)$ such that $\pi_1(C,c)\cong H$.
The thing that is clear is that $\pi_1(C,c)$ is congruent to a subgroup of $\pi_1(X,x)$. Since $\rho^*$ is injective.

A: According to Proposition 1.3.6 of Hatcher's Algebraic Topology,

Suppose $X$ is path-connected, locally path-connected and semilocally simply-connected. Then for every subgroup $H \subseteq \pi_1(X,x_0)$, there is a covering space $p : X_H \rightarrow X$ such that $p_* \pi_1(X_H, \tilde x_0) = H$ for a suitably chosen basepoint $\tilde x_0 \in X_H.$

At least some sort of condition is necessary, as the well-known Hawaiian earring space (for example) has no universal cover and so this result fails. Of course the condition of being simply-connected is much too strong to be interesting here.


text:
Q: force ssl with .htaccess while rewriting addresses I am currently using this .htaccess to redirect all the requests for pages with a directory to my index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ /seattle/index.php/$1 [L]

And this works just fine and produces urls that hide the index.php, and I have code in index.php that makes urls clean looking.
But now I need to force pages to connect via ssl, so I tried
RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ https://example.com/seattle/index.php/$1 [L]

and it works to force ssl, but now it also forces the url to include the index.php:
https://example.com/seattle/index.php/pagename

instead of what I want
https://example.com/seattle/pagename

What am I missing?

A: To change protocol (HTTP -> HTTPS) and/or domain name (www.example.com -> example.com) the proper redirect ("301 Permanent Redirect" or "302 Found/Temp Redirect") is required.
Therefore you cannot combine rewrite and redirect and still showing original URL. It has to be 2 different rules and the one for changing protocol/domain should be listed first. For example:
RewriteEngine on

# force HTTPS for all URLs
RewriteCond %{HTTPS} =off
RewriteRule . https://example.com%{REQUEST_URI} [R=301,L]

# other rewrite rules
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ /seattle/index.php/$1 [L]

The rule I have added will redirect ALL HTTP URLs to HTTPS. If you need only some of them to be redirected -- add appropriate conditions via additional RewriteCond line(s).
The %{HTTPS} is the most common and kind of "proper" way of checking if SSL is ON or OFF (but it is all depending on your specific circumstances and server config). When checking against %{HTTPS} you are safe against situation when your site is running on non-standard port (other than 80). You can use %{SERVER_PORT} =80 instead (will work for majority of cases).
With the above rules the rewrite for http://example.com/seattle/pagename will occur in 2 steps:

*

*301 Redirect to https://example.com/seattle/pagename

*Rewrite (internal redirect) to /seattle/index.php/pagename


text:
Q: How to set some angle or line tolerance in using Hough transform for detecting horizon line on marine images So I have a dataset of about 3000 images and about 7% of them is poorly processed. I'm using OpenCV and Python and my algorithm is based on preprocessing with morphological erosion, Canny edge detection and Hough line transform. On some images horizon line is not detected because Canny returns a line with a gap or a horizon which isn't a straight line. Is there a way to fix it? Perhaps adding a tolerance to the angle or something like that? Probabilistic Hough transform doesn't help either.
Here is an original image and successfully processed one:

And here is a troubled pair:

import cv2
import numpy as np
img = cv2.imread(conf.data_folder + 'frame0134.jpg',0)
kernel = np.ones((9,9),np.uint8)
erosion = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
edges = cv2.Canny(erosion,50,150)
lines = cv2.HoughLines(edges,1,np.pi/180,80)
for ro, theta in lines[0]:
  if theta == 0.0:
    x1 = int(ro)
    x2 = int(ro)
    y1 = 0
    y2 = img.shape[0]
    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
    cropped = img[:,0:x1]
  else:
    a = -1/np.tan(theta)
    b = ro/np.sin(theta)
    y1 = 0 x1 = max(0, int( -b/a))
    y2 = img.shape[0]
    x2 = min(img.shape[1], int((y2-b)/a))
    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)


text:
Q: Overriding the QGIS Feature Dialog We are developing a QGIS plugin and would like to override the QGIS Feature Edit Form with our own Dialog.
Have explored using setEditForm and setEditFormInit, but the init process appears to want to use a python file located in the user's project directory.
Ideally we'd use an init method from our Plugin's code and gain access to our Plugin's instance.
Had thought that the new EditWidget V2 might be able to help, but this seems to be focussed on editing individual attributes rather than a feature.
UPDATE
Doh. Managed to resolve it.
In the init method of your plugin:
Firstly add the plugin directory to the system path list (or a subdirectory of it)
Secondly, initialise a static variable with the Plugin's instance (self)
Am yet to add logic to the dialog but looks like we're on the home run.  Thanks Python!


text:
Q: Why don't we put parentheses in the function of setInterval in javascript?

    <title>INTERVAL</title>

    <button type="button" onclick="func()">CLICK IT</button>

    Time:

here

Here, in the line [var inter = setInterval(func,2000);] , why dont we use func() instead of func ?

A: You don't put parentheses after func in setInterval because setInterval(func(), 2000) would try to call the return value of func as a function instead of calling func itself.

A: Using parentheses with functions means I want to call the function and if it returns a result, I want it.
int func() { return 1337; }
let x = 10 + func();

What about if I want to pass the function as argument so that I want to call it in my internal side? I don't want its result or internal process at its calling time but later.

A: setInterval expects the reference to a function, which will be called once the time you passed is elapsed.
in your example func is a function reference and func() is how you call the function, and in your case, setInterval will take care of the calling part.

A: I think you're looking for the difference between a function call and a function declaration.
A function declaration is the body of a function itself.
A function call says do the thing described in the function declaration.
func = function declaration
func() = call function func
() means do this now in javascript. If you put it after a function declaration, it means do the proceeding function declaration now. But you can also use it to perform inline operations. let a = (1 + 2)  * 3;
setInterval is looking for a function declaration, which it will call. So passing it a function call would be redundant, and thus fail.


text:
Q: MobileApps Security Issue I've a very compelling question to begin first. But this is not about code level, it's just for me to gauge my understanding. Correct me if i'm wrong, now days MobileApps as per design utilizes the session token method for a request.
Currently, for first time user will pass in their deviceID, pin, and timestamp for an encrypted value from the back-end. Subsequently , the front-end system will send this parameter for request and get a response success. The token has expiration date of 30 minutes.
With a recent event, hackers are able to manipulate the request from a script by spoofing. So the hackers are imitating the same behavior as from mobileapps. How do we cater for this kind of scenario? Is there a way to block these kind of request ?

A: Token Method

Correct me if i'm wrong, now days MobileApps as per design utilizes the session token method for a request.

I think you are referring to OAUTH2 or OpenID tokens.
OAUTH2

OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.

OpenID

OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
OpenID Connect allows clients of all types, including Web-based, mobile, and JavaScript clients, to request and receive information about authenticated sessions and end-users. The specification suite is extensible, allowing participants to use optional features such as encryption of identity data, discovery of OpenID Providers, and session management, when it makes sense for them.

Mobile App Identification to the API

Currently, for first time user will pass in their deviceID, pin, and timestamp for an encrypted value from the back-end. Subsequently , the front-end system will send this parameter for request and get a response success. The token has expiration date of 30 minutes.

Normally developers identify the mobile to the API server with a secret that is normally called api-key or some kind of named token *-token. No matter what the convention name used this is identifier is always a secret that sometimes is a simple unique string to identify the mobile app and sometimes is more sophisticated, like in your case.

With a recent event, hackers are able to manipulate the request from a script by spoofing.

The problem is that anything running in the client side can be reverse engineered
easily by an attacker on a device he controls. He will use introspection frameworks like Frida or xPosed to intercept at runtime the running code of the mobile app or will use a proxy tool like MiTM for watching the communications between the mobile app and the API server. Normally their first step in reverse engineer a mobile app will be to use the Mobile Security Framework to reverse engineer the binary of you mobile app to extract all static secrets and to identify attack vectors.
Frida

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

xPosed

Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo.

Mobile Security Framework

Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.

MiTM Proxy

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

So after using all this tools is possible for an attacker to replay all steps your mobile app does to get the token from the API server and use it afterwards to automate the attacks against the API server.
Possible Solution

So the hackers are imitating the same behavior as from mobileapps. How do we cater for this kind of scenario? Is there a way to block these kind of request?

So anything that runs on the client side and needs some secret to access an API can be abused in different ways and you can learn more on this series of articles about mobile api security techniques. This articles will teach you how API Keys, User Access Tokens, HMAC, TLS Pinning can be used to protect the API and how they can be bypassed.
A better solution can be employed by using a Mobile App Attestation solution to enable the API server to know is receiving only requests from a genuine mobile app.
A Mobile App Attestation service will guarantee at run-time that your mobile app was not tampered or is not running in a rooted/jail broken device by running a SDK in the background(without impacting user experience), that will communicate with a service running in the cloud to attest the integrity of the mobile app and the device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must send with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny. Your current token could be used as a payload claim in the Approov Token to allow the API server to continue using it with the guarantee that was not tampered with.


text:
Q: Run evaluation after part of a training epoch I load two datasets with the dataset api, one for training and one for evaluation. I switch between them with sess.run(train_init_op) before running the evaluation or training.
Currently I run the evaluation after finishing one epoch, i.e. after the training dataset was run through completely.
If I want to evaluate my network before the training dataset was finished, I would have to switch earlier, and by doing this tensorflow would forget where it has been in the training dataset. Is there any way to remember the state of the training dataset iterator? And switch back to this position after the evaluation has finished?

A: I think it is not only about remembering the position in the training set, but also accumulated gradients, params of an optimizer (if you use something like Adam) etc. Switching context between training and validation can be tricky.
For instance, in Google object detection API there is a separate validation process that monitors for fresh checkpoints and run validation on them. Meanwhile training is running further. Thus, by setting the checkpoint interval you can achieve any validation frequency you want.


text:
Q: Javascript content manipulation For example I've got the got a random HTML code:

javascript

bla bla

With its sample1.js code:
var a = 1234;
var b = 0.2;

console.log("this a simple script");
console.log(a * b);

I would like to know if is there any possibility to find all integers and floats from sample1.js and after executed to re-execute the same content but with any other random generated int or float values.
To sum up, I would sample1.html file to refresh but with sample1.js to contain any other random values for a and b

A: After execution I would the page to be automatically reloaded but all the integers and floats in the page to be randomized with other values.
I know I can statically analyze the code. Image I have a very long functionality test script which tests various functions. I would like to add a custom function which parses all integers and floats in my page and then reload the page automatically with messed up values for my variables.


text:
Q: Can a string array parameter be inserted into a table [variable] defined in the command of the report? I have an array parameter that I need to represent column names for a report. I have a command that queries the database for data and pivots it. I wanted to pass in the columns.  The part I am having trouble with is adding the parameter values to the temp table that holds the column names.
This example does not work but I am hoping it gives an idea what I am after
So, the ?Fields parameter is my array....
Thanks!!
-- test parameters
declare  @tab table(field
varchar(100))

 -- insert into @tab   values('John'),
 -- ('Sarah'),('George')

 insert into @tab
 VALUES ({?Fields})

 SELECT * FROM @tab


text:
Q: Is this foreach loop responsible for god killing cats? As taken from https://stackoverflow.com/questions/4891301/top-bad-practices-in-php
Is this similar code killing kittens, too?
foreach (file("longFile.txt") as $line) {
    // ouch! Kitten killed
}

??
For those who have no idea what am I talking about:
Is PHP getting longFile.txt everytime it goes to next line of file or no? Talking about this code:
foreach (file("longFile.txt") as $line) {
        // something
}

A: In the linked question the for loop incurs a performance hit by calling count on every iteration. foreach uses internal pointers to iterate through the array passed to it.
In your example file() will be called once and the resulting array will be passed to foreach which will iterate through it, thus the kittens are saved. Happy Caturday!

A: It shouldn't be killing any kittens, since, in order for PHP to get the following line of the file, it has to know the position of the file pointer since the previous line that was pulled off. You are only advancing the iterator, which maintains a reference to the file object.
Also, it's bad practice to be opening a file like that; you should have a variable to store it in and close it when you're done.

A: Is that file really large? Consider:
foreach(new SplFileObject($path) as $line) {
    // neither kill puppies nor kittens
}

foreach works always on the concrete iterator. If you're passing an array:

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. (ref)

So nor array or function call will executed each time the foreach steps ahead.
Related: How to store and reset a PHP array pointer?

A: You want to use a Duff Device to unroll the loop: http://de.wikipedia.org/wiki/Duff%E2%80%99s_Device. This would be faster then foreach and faster then for loop without using count() on each iteration and it would be faster then concatenating and rtrim the string but the same like using implode().

A: No. There are many reasons why kittens die, but foreach loops are not one of them.


text:
Q: JQuery .serializeArray() drops text after < in input box Using .serializeArray()  and if I enter say Jim<Test in a text box, only Jim is picked up by Jquery. Is their a work around?
Thanks!

A: Working demo http://jsfiddle.net/xyBS3/
I cannot see the code by you,but you can try typing jim<test and it will allow you to do that.
Hope it helps the cause. :)
code
$('pre').text(JSON.stringify($('#f').serializeArray(), null, '  '));

$('input').keyup(function() {
    $('pre').text(JSON.stringify($('#f').serializeArray(), null, '  '));
});


text:
Q: Installing and using npm (Node.js) module on Windows 2008 server Can someone please advise - how to resolve this?  This setup works fine locally on Windows 7 laptop, but fails on Windows 2008 server.
Here is the setup:
1.  Using ASP.NET Core App and NodeServices on Windows Server 2008.
2.  Installed Node.js and NPM on the server.
Logged in as one of the admin accounts "xyz".  When I install a npm module - in this case, cypress test framework, it installs under the path:
C:\Users\xyz\AppData\Local

But when I run the application, it looks for the module under the path:
C:\Windows\system32\config\systemprofile\AppData\Local\Cypress\Cache\3.1.5\Cypress\

The application fails, complaining that the module is not found.
Things I tried so far:
1. Copied the cypress module directly from user localappdata folder to above location.  Then it works.
2.  Tried giving full path to the var cypress = require('cypress') - it finds the module, but whenever we try to use cypress, gives the same error.
3. Tried changing the nom prefix as well as cache location to the above path, but npm install cypress always installs under user's localappdata path only.
Any ideas on how to - either make the npm install, install the module at desired location. OR make the application look at the desired path?
Thanks a lot.
Here is the error:
An unhandled exception occurred while processing the request.
NodeInvocationException: No version of Cypress is installed in: C:\Windows\system32\config\systemprofile\AppData\Local\Cypress\Cache\3.1.5\Cypress

Please reinstall Cypress by running: cypress install
----------

Cypress executable not found at: C:\Windows\system32\config\systemprofile\AppData\Local\Cypress\Cache\3.1.5\Cypress\Cypress.exe
----------

Platform: win32 (6.1.7601)
Cypress Version: 3.1.5
Error: No version of Cypress is installed in: C:\Windows\system32\config\systemprofile\AppData\Local\Cypress\Cache\3.1.5\Cypress

Please reinstall Cypress by running: cypress install
----------

Cypress executable not found at: C:\Windows\system32\config\systemprofile\AppData\Local\Cypress\Cache\3.1.5\Cypress\Cypress.exe
----------

Platform: win32 (6.1.7601)
Cypress Version: 3.1.5
at raise (C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\errors.js:161:13)
From previous event:
at C:\inetpub\wwwroot\EmbeddedDashboard\node_modules\cypress\lib\errors.js:169:37
at C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\tasks\verify.js:48:60
From previous event:
at checkExecutable (C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\tasks\verify.js:43:11)
at C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\tasks\verify.js:213:12
at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
at Object.start (C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\tasks\verify.js:212:6)
at Object.start (C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\exec\run.js:130:19)
at C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\cypress.js:29:19
at _fileCreated (C:\inetpub\wwwroot\projectTest\node_modules\tmp\lib\tmp.js:246:7)
at FSReqWrap.oncomplete (fs.js:82:15)
From previous event:
at Object.run (C:\inetpub\wwwroot\projectTest\node_modules\cypress\lib\cypress.js:26:28)
at module.exports.cypress.run.then (C:\inetpub\wwwroot\projectTest\Scripts\RunTests.js:4:13)
at C:\Windows\TEMP\mecqsmig.e5o:166:18
at IncomingMessage.<anonymous> (C:\Windows\TEMP\mecqsmig.e5o:186:37)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance.InvokeExportAsync<T>(NodeInvocationInfo invocationInfo, CancellationToken cancellationToken)

A: Cypress uses cachedir to find the correct location to install Cypress into. C:\Windows\System32\config\systemprofile is the home folder of the SYSTEM user on Windows. Somehow, npm install is being executed as SYSTEM, not as your user. This would cause Cypress will attempt to install to SYSTEM's %APPDATA% directory, which is C:\Windows\System32\config\systemprofile.

A: This would make sense, according to the system requirements of Cypress:

Windows 7+, only 32bit binaries are provided for Windows.

A: I figured out how to resolve this.  For some reason, when I run the application, even though it is configured to run under a service account, it still kept using the default system location for cache location.
You can configure the cache location of Cypress by setting an environment variable to your desired location.  That resolved the issue for me.  Here is the link to it:  https://docs.cypress.io/guides/getting-started/installing-cypress.html#Binary-cache
Basically, you set a value to this environment variable CYPRESS_CACHE_FOLDER and you are set.
Hope this helps someone.


text:
Q: Using List to array cast and passing it to inflater import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class Main extends ListActivity implements OnClickListener  {
    final String [] MyName = new String [1000];
    ArrayList<String> myArr = new ArrayList<String>();
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        while (people.moveToNext()){
            int NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            String Name = people.getString(NameIndex);
            MyName[i] = Name.toString();
            myArr.add(Name.toString());
            i++;
        }
            setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1,
                    R.id.textView1,
                    myArr.toArray()));

    }

         class MyAdapter extends ArrayAdapter<String>{

                public MyAdapter(Context context, int resource,
                    int textViewResourceId, Object[] objects) {
                    super(context, resource, textViewResourceId, (String[]) objects);
                    // TODO Auto-generated constructor stub
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    LayoutInflater inflater =  (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View row = inflater.inflate(R.layout.custom_view, parent,false);
                    TextView tv = (TextView) row.findViewById(R.id.textView1);
                    tv.setText(myArr.get(position).toString());
                    return row;
                }
        }

Hello I am trying to implement a List myArr containing contact names in the phone directory. The size varies along with the number of contacts. after finishing the list creation and adding all contacts i passed the list myArr to the seListAdapter function. The problem faced in this code is that it is showing an error on launch in the emulator. how can i pass the entire list myArr to the method and then display each name separately in the inflater textview
i have searched for the myArr.functions and only found myArr.get() returning only one element

A: Convert it as the following:
(String[]) myArr.toArray(new String[]{});


text:
Q: Create a section rule that is the same width as the section title I would like to create something that looks like this:
Now, I have seen a solution that works with the asker's example environment (using \predisplaysize). However, my desired solution is a little different. In particular, I am trying to use \titleformat:
\documentclass[12pt]{article}

\usepackage{xcolor, lipsum}
\usepackage[calcwidth]{titlesec}

\definecolor{carmine}{rgb}{0.68, 0.0, 0.09}

\titleformat{\section}[hang]{\Large\sffamily\bfseries}
{\color{carmine}\S$\,$\thesection}{0.5em}{\color{black}}
%This creates a rule that matches the full page's width, rather than the title's
[\vspace{-1.5em}\rule{\textwidth}{0.2pt}]

\begin{document}
\section{Introduction}
\lipsum[1-1]
\end{document}

This looks like:

So far, my attempts to use the titlesec have been unsuccessful. When using \titlewidth as an argument to \rule, I find that the underline completely disappears. As well, the example given in the documentation draws a rule (of full page width) above the section name.
Is there a way to create a rule under a section title that has the same width as the title?

A: This is not very good style, but here we go…
The documentation mentions there can be wrong measurements of  titles with the hang option (which b.t.w. is the default). You can use the block style, which is the same as hang as long as you don't have multiline titles.
Also, I suggest using the [T1] font encoding, as this will load cmsuper which has a bold version of §, and I don't think yopu want to raise the rule by 1.5em: this would make it strike through the title.  1.5ex is more sensible.
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{xcolor, lipsum}
\usepackage[calcwidth]{titlesec}

\definecolor{carmine}{rgb}{0.68, 0.0, 0.09}

\titleformat{\section}[block] {\Large\sffamily\bfseries}
{\color{carmine}\S\,\thesection}{0.5em}{\color{black}}
%This creates a rule that matches the full page's width, rather than the title's
 [\vspace{-1.5ex}\rule{\titlewidth}{0.2pt}]

\begin{document}

\section{Introduction.}

\lipsum[1-1]

\end{document}

Note:
If you do have multiline section titles, there exists a workaround to make titles hang with the block style.


text:
Q: Not able to Downloading Files using Google Drive API V3 I am facing issue "Call to a member function getBody() on string"
I am using following code
 public  function downloadFile($fileId , $name)
{
  try
  {
       $content = $this->service->files->get($fileId, array("alt" => "media"));
       $outHandle = fopen(APPPATH ."Downloads". "/" . $name , "w+");
       while (!$content->getBody()->eof()) {
            fwrite($outHandle, $content->getBody()->read(1024));
      }
       fclose($outHandle);
        return $outHandle;
    } catch (\Exception $e) {
  }

}

A: This option may be a little simpler.
$file = $service->files->get($fileId, array('alt' => 'media'));
file_put_contents($file->name, $file->getBody());


text:
Q: 1D Random walk with state-dependent move probability We start with $a + b$ balls in the urn: $a$ white and $b$ black ones.At each step we randomly choose a ball and if it's white then $m$ of the black balls in the urn turn white, symetrically for choosing black one. We put the chosen ball back in the urn. So if we've chosen white we move from $(a,b)$ state into $(a+m, b-m)$. What is the probability that at $k$ step we will choose a white ball?
So my understanding is that this is a kind of random walk on 1D with state $l$ representing the urn of $(a + lm, b-lm)$ and reachable only from states $\{l-1, l+1\}$ but the probability of the move is state-dependent and I've got stuck here.


text:
Q: Customize month name in Datepicker Ng bootstrap I need to customize the Month name, which is currently abbreviated to show the full name
It currently looks like this:

and I wish it to be like this:

And I would also like to remove the dot.

A: You has an example in Internationalization of datepickers
You create a CustomDatepickerI18n that extends NgbDatepickerI18n with the functions:
  getWeekdayLabel(weekday: number): string
  getWeekLabel(): string
  getMonthShortName(month: number): string
  getMonthFullName(month: number): string
  getDayAriaLabel(date: NgbDateStruct): string

And use as provider in your module (or in your component)
providers:
      [{provide: NgbDatepickerI18n, useClass: CustomDatepickerI18n}]


text:
Q: Debugging refused ssh connection to EC2 instance I have created a new EC2 instance api1-new in the same subnet, same VPC and using the same security groups as an old instance api1-old. api1-new was created from an Ubuntu Linux AMI that already has several users pre-configured, and additionally, I launched it with an Amazon key pair.

*

*I cannot connect by ssh -vvv -p Y my_alias nor ssh -vvv -p Y X.X.X.X from my bastion server, which is in a different subnet from the api1 instances. The first and only error message in the ssh output is:

debug1: connect to address X.X.X.X port Y: Connection refused

*I can connect to api1-old from the same bastion server using the same port, logged in as the same user as in 1.

*I can connect to api1-new from my gitlab runner, which is in a third subnet, logged in as the same user as in 1.

*I can connect from the same bastion server, logged in as the same user, to an instance launched (some time ago, by a colleague) from the same AMI as api1-new into the third subnet.

*I have placed default ACLs (all traffic allowed) on all three subnets involved, but still cannot connect.

*When I add a ping security group to api1-new, I can ping to it from the bastion server, logged in as the same user as in 1.

*The $HOME folder, $HOME/.ssh folder and $HOME/.ssh/authorized-keys are rigorously the same (permissions and content) on api1-new, api1-old and on the server mentioned in 4.

*I cannot connect from the bastion server to api1-new using the Amazon key pair I created for launching api1-new, whether connecting as ubuntu or as my normal user. The MD5 fingerprint of the private key on the bastion server is identical to what I see in the system log of api1-new.
The api1 instances don't have public IP addresses.
I feel I am missing some part of the puzzle in addition to security groups, ACLs and authorized_keys.
I wonder if there is some way to log refused SSH connections on api1-new to get the reason why the connection was refused.
Thanks to wesleywh for the suggestion to look at /etc/ssh/sshd_config!

A: I don't think this has anything to do with your subnets or ssh keys. The fact that you're getting a "connection refused" makes be think your bastion instance is able to see your other ec2 instance just fine. The issue is probably the security group on the "other ec2 instance" itself or how you're supplying your keys.
Open the "other ec2 instance" security group. If your trying to access this instance from port 22 from bastion then add the following to the inbound rules on the "other ec2 instance":
Type | Protocol | Port Range | Source      | Description
-----------------------------------------------------------
SSH  |  TCP     |     22     |  sg-1234abc |  Bastion SG

Where sg-1234abc is the security group id of your bastion ec2 instance. Then try it again.
--- FROM LOCAL MACHINE ---
ssh-add -k <path_to_aws_private_key>
ssh-add -k <path_to_bastion_user_private_key>
ssh -A <bastion_user>@<bastion_ip>

--- FROM INSIDE BASTION INSTANCE ---
ssh ec2-user@<other ec2 instance ip>

EDIT: Per the comments below also check the following:
Look at /etc/ssh/sshd_config and make sure it's set to accept a custom ssh port if you're planning on using one.


text:
Q: (Tcl/Tk) Creating a persistent options window? Stackoverflow!
My issue here is two-part; the first part is I have no idea what this concept is actually called which is why I had an incredibly difficult time searching for it anywhere! Part two is I'm not sure how it would be implemented in Tcl/Tk. Here goes...
So how would one make one of those persistent "settings" toplevels where you have to finish what you're doing in that window either by clicking "cancel" or "ok" before you can return to the main GUI? I understand I can give a window the topmost attribute with the wm attributes which will keep the window on top of ever other window, but that's not quite what I want.

A: To make a modal dialog in Tk, you need to set a grab so that mouse events are directed to the dialog window. You probably also need to make sure that the focus is somewhere in the dialog. (Don't use a global grab — grab -global — unless you know what you're doing and are very careful; you can lock your whole GUI from user interaction with that. You should not use global grabs for modal dialogs.)
Grabs can only be set on mapped windows. On Unix, the tkwait visible command is perfect for making things pause momentarily until the window is actually mapped. On Windows and OSX, it doesn't really work though an appropriate after can help a lot, as can watching for the first time an <Expose> event is processed (which is what an actual draw of the dialog is postponed to).
You might also want to look at using tkwait variable (a.k.a., vwait) so that you can use the dialog in a blocking fashion from within your code; you just set the (global!) variable from the OK and Cancel buttons. It's not necessary, but it's a reasonably common pattern. If you do that, make sure that if the user just closes the dialog by clicking on its X window decoration, you still terminate the wait. The <Destroy> event is useful for that (though be careful with trapping a <Destroy> on any toplevel; it also detects destruction of child widgets).
Finally, a reasonable place to start looking at how to do this is Tk's own tk_dialog command. It's just a procedure, so you can read the source easily. Or you can look online (particularly check from line 148 onwards). The procedures it calls are all in tk.tcl…


text:
Q: zsh: How to store the return code of a statement without triggering `set -e`? Suppose I want to capture the return code of
(exit 56)

If I use set -e or a zerr handler, I can no longer do:
(exit 56)
ret=$?

If I use (exit 56) || true to avoid set -e, the return code would become zero and I can no longer get it.
So how do I get the return code?

A: You can use && true instead:
set -o errexit
(exit 50) && true
echo code: $?

Though you could also do:
set -o errexit
if (exit 50) then else
  echo failed with code $?
fi

Or:
set -o errexit
(exit 50) || {
  code=$?
  echo failed with code $code
  # and whatever else you want to do with $code
}

The idea is that errexit is cancelled whenever the failing command is used as a condition, but if you do (exit 50) && true, the exit code after that would always be 0.
(personally, I avoid errexit and prefer doing proper error handling by hand).


text:
Q: How to know eclipse has web tools plaform I am using the juno eclipse and i want to install the wtp for the xml editor. But i am confused whether web tool is already install or not.
2) which is best free plugin for the xml editing in the eclipse.
Any help will be appreciated.

A: Rinzo XML Editor
OXygen XML Editor
Altova XML Editor
Exciting XML Editor


text:
Q: Copy multiline formatted text into a single cell in Excel My question is similar to Copying a multiline text into a single cell in Excel, except that the text I want to copy contains rich text formatting - bold text, colored text, bullet items, etc...
If I double-click in the cell, or click in the formula bar, before pasting, as directed in the linked question's answer, it does preserve the line breaks, but all other formatting is lost; it treats the paste as a plaintext paste.
Is there any way to copy formatted, multiline text from a web page, an email, MS Word, or any other program, into a single cell in Excel?
As an example, suppose I want to copy the following text directly out of this web page, and paste it all into one cell of my workbook, while preserving the line breaks and formatting:

How to make a sandwich:

*

*2 slices of bread

*one slice of meat

*one slice of cheese

  Put the meat on one of the bread slices. Put the cheese on top of
  that. Put the other bread slice on top of that.
Voila!

Here are several screenshots of ways I tried to accomplish this by copying from a table in a Microsoft Word document into Excel using various options. The text A1, B1, etc. indicate the cells I expect the text to end up in.
In Word, with formatting characters displayed:

Using default Paste into Excel in cell A1. Note that Excel broke the text at both the hard (¶) and soft returns (↵) into separate rows, and created merged cells for the "A1" and "C1" text:

Using "Match Destination Formatting" paste option into Excel, in cell A1:

Double-clicking inside cell B1, then pasting (note that no "Paste Special" options are available with this approach):

And here, I noted all of the character formatting Excel applied when using the default paste, and manually applied it to the text in order to illustrate my desired result. Excel does not offer bullet formatting, but when using the default paste, it puts the bullet symbol in 11.5 pt Symbol font, and reproduces the Tab from Word with several space characters in 7 pt Times New Roman. The only thing that can't be applied to a subset of the text in a cell is the indented alignment, but even without that, to get a paste result like this, without having to manually apply the font, size, bold, and italics everywhere, every time (and color, if applicable), would be ideal:

A: I've been looking and looking for answers to exactly this problem: I have a formatted Word doc I need to use as front matter to my spreadsheet, and I just desperately wanted to copy paste the data in easily. The Word Object option doesn't let you click the hyperlink unless you open the embedded Word file, so the initially visible links aren't clickable. I finally stumbled upon the solution all on my own: use a text box. Why do you really need a cell for stuff like this? Just use a text box.

A: Easy solution:

*

*Convert your formatted text in MS Word to a table. Select the text, from the  Insert tab > Table > Convert Text to Table.  Remember that any text after a (hard) return in your text will form a new table row. You can replace them with soft returns (shift enter) if you like.

*Copy your MS Word table cells into Excel.

*Voila!

A: I have been wanting to do this for a long time too.
I started playing around with Excel and noticed the Insert Word Object will do what you want.
Here is a link that explains the different ways to Insert Objects.
https://support.office.com/en-gb/article/insert-an-object-in-your-excel-spreadsheet-e73867b2-2988-4116-8d85-f5769ea435ba
The "Create a new object from inside Excel" appears to be what you want.
The one draw back I see is the Cell will not auto-resize when the Object size changes so you will have to manually resize the cell size.

A: *

*Select the target table in Word.

*Press Ctrl+H to open 'Find and Replace' dialog box.

*Type ^p in 'Find what:' text box and in 'Replace with:' text box, type some unique text or character that does not occur in the text in your table, like ~~~ or |

*Press Replace All button.

*Close the 'Find and Replace' dialog box.

*Copy the table in Word and Paste it into Excel.

*Now press Ctrl+H in Excel to open 'Find and Replace' dialog box.

*Enter ~~~ or | (or whatever you used in Word table) in 'Find what:' text box and place cursor in 'Replace with:' text box and press Alt+0010.

*Press Options>> button and ensure that the 'Match case' and 'Match entire cell contents' check boxes are not checked.

*Press Replace All button.

A: Open the PDF.
Select the text required and Copy (to clipboard). (Ctrl c)
Open Excel.
Select the cell you want to paste into.
Don't paste into the cell, but paste into the Formula bar window. (Ctrl v)
Your text should now appear in your selected Cell. Any Carriage Returns (CR) will now start a new line within the cell.
If you want another CR within the cell, press Alt Return where you want the CR. Otherwise Return just selects the next cell.
If you want to "lose" a CR, just delete like any other character.
Hope this helps.


text:
Q: MSACCESS - At most one record can be returned by this subquery Please help me fix this SQL Query:
SELECT DISTINCT [ClassSessions].Shortcode
    ,[CertIV_BC_A].ID
    ,[CertIV_BC_A].Units
    ,[CertIV_BC_A].AT
    ,Format((
            SELECT DATE
            FROM ClassSessions
            WHERE [ClassSessions].[Code] = [CertIV_BC_A].[SessionStart]
                AND ([ClassSessions].[OccurenceID] = '34849')
            ), 'dd/mm/yy') AS StartDate
    ,[CertIV_BC_A].SessionStart
    ,[CertIV_BC_A].SessionEnd
FROM CertIV_BC_A
    ,ClassSessions
WHERE (([ClassSessions].[OccurenceID] = '34849'))
ORDER BY [CertIV_BC_A].ID;

These are the 2 databases:
CertIV_BC_ACert IV_BC_A_Database

ClassSessions
ClassSessions Database
The Query work when there is only 1 OccurenceID in ClassSessions Database. However when there are more than 1 OccurenceID in ClassSessions, I get the error.
This is the result of the query
Module  ID  AT  StartDate   EndDate

*

*List item

*Module 1 1   AT1 5/10/2017   31/05/2017

*Module 1 2   AT2 24/05/2017  26/06/2017

*Module 1 3   AT3

*Module 1 4   AT4

*Module 1 5   AT5

*Module 2 6   AT1 28/06/2017  28/08/2017

*Module 2 7   AT2 28/06/2017  8/07/2017

Please let me know if I need to supply more details. Thank you very much

A: select top 1 or max date from your subquery
SELECT DISTINCT
  [ClassSessions].Shortcode,
  [CertIV_BC_A].ID,
  [CertIV_BC_A].Units,
  [CertIV_BC_A].AT,
  Format(
   (SELECT
    MAX(Date)
    FROM ClassSessions
    WHERE [ClassSessions].

   [Code] = [CertIV_BC_A].[SessionStart]
    AND ([ClassSessions].[OccurenceID] = '34849')), 'dd/mm/yy') AS StartDate,
  [CertIV_BC_A].SessionStart,
  [CertIV_BC_A].SessionEnd

FROM CertIV_BC_A,
     ClassSessions
WHERE (([ClassSessions].[OccurenceID] = '34849'))

ORDER BY [CertIV_BC_A].ID;

A: I'd put the Format inside the subquery.
,(
    SELECT Format(DATE, 'dd/mm/yy')
    FROM ClassSessions
    WHERE [ClassSessions].[Code] = [CertIV_BC_A].[SessionStart]
        AND ([ClassSessions].[OccurenceID] = '34849')
  ) AS StartDate


text:
Q: JavaScript  to a  and its children I this simple website Im trying to develop, but I have never used Javascript before.
I have a menu that is based on href to div tags on my site to the different agreements with different companies. So when the user click a choice in the menu the right div item fades in.
Now I want to make the site more practical with google maps api for each company.
So I need to  in the menu to display more than just one
 item. I have tried to solve this by using a
 inside the
 item. Since I want to have the company description on the left hand og the google map + short description on the right hand. But now I have decided that I want to use
 items with display properties instead of a
 inside a
 item.
Here is the code just made simple without the php code to gather info from DB:
http://jsfiddle.net/nerfux/546Jn/7/
As you see, category2 -> company3, is the messy solution I made. In the HTML code at
 and
, I have commented out the solution I want to use.
So, a short way to say it: When I click a href to a div item, I want also to fadeIn all the
 items underneath the
 item I  to (regardless if they have an id or not).

A: If you just want to hide the wrapping container (.content), and not the divs inside, you can just add > to the selector. It will only affect the div directly under .content.
So add > to
$('.content div')
like so
$('.content > div')


text:
Q: Use installed a 3rd party file explorers. How do I get the register default explorer program via win32? I guess it's like total commander or similar type program where they replace the default folder browser. How do I know via win32, what replacement program the user is used instead of explorer.exe

A: There's no officially supported mechanism in Windows for changing the default folder browser.
However anything that does "replace Explorer" has to set itself as the default action for the HKEY_CLASSES_ROOT\Folder key, so I would start by looking there.