text:
Q: Change font color in Emacs ansi-term mode I am using Emacs 24.5.1
In ansi-term mode, the font color of folder is quite unreadable (I am wearing a pair of anti-blue light glasses), well, I hope to get rid of this color, because of the same reason.

(Blue color is almost invisible through the anti-blue glasses)
Any ideas?

A: You can change colors of both the term and ansi-term modes by customizing the term group. The steps are as follow:

*

*First, run the command customize-group by typing M-x customize-group

*And then type the term group
Now, you are free to change the color of the ansi-term mode. For example, to change the color of folders, in my Emacs setting, I can chang it by modifying the Term Color Green face option.

A: term-mode tries to be just like other terminals, like xterm, which have the same problem.  I like dark backgrounds, which means the standard blue color is hard to see.  I solved this for all terminals by customizing the colors of the terminal apps that I use regularly.
# set up colors for ls
function set_up_dircolors() {
    local dircolors=dircolors
    if ! $is_GNU ; then
        dircolors=gdircolors
    fi

    if is_command $dircolors ; then
        if [ ! -e $HOME/.dircolors ] ; then
            $dircolors --print-database > $HOME/.dircolors
        fi

        eval $($dircolors --sh $HOME/.dircolors)
    fi
}
set_up_dircolors

export GREP_COLORS="ms=01;32:mc=01;32:sl=:cx=:fn=35:ln=32:bn=32:se=36"

is_GNU is a (hacky) test to see if I'm on BSD or not, roughly bash --version | grep -i bsd.
Here's the ~/.dircolors config file:
# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option.
# Copyright (C) 1996, 1999-2010 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted provided the copyright notice and this notice are preserved.
# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
# slackware version of dircolors) are recognized but ignored.
# Below, there should be one TERM entry for each termtype that is colorizable
TERM Eterm
TERM ansi
TERM color-xterm
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28
TERM con80x30
TERM con80x43
TERM con80x50
TERM con80x60
TERM cons25
TERM console
TERM cygwin
TERM dtterm
TERM eterm-color
TERM gnome
TERM gnome-256color
TERM jfbterm
TERM konsole
TERM kterm
TERM linux
TERM linux-c
TERM mach-color
TERM mlterm
TERM putty
TERM rxvt
TERM rxvt-256color
TERM rxvt-unicode-256color
TERM rxvt-cygwin
TERM rxvt-cygwin-native
TERM rxvt-unicode
TERM rxvt-unicode256
TERM screen
TERM screen-256color
TERM screen-256color-bce
TERM screen-bce
TERM screen-w
TERM screen.linux
TERM vt100
TERM xterm
TERM xterm-16color
TERM xterm-256color
TERM xterm-88color
TERM xterm-color
TERM xterm-debian
# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#NORMAL 00 # no color code at all
#FILE 00 # regular file: use no color at all
RESET 0 # reset to "normal" color
DIR 01;36 # directory
LINK target # symbolic link. (If you set this to 'target' instead of a
 # numerical value, the color is as for the file pointed to.)
MULTIHARDLINK 00 # regular file with more than one link
FIFO 40;33 # pipe
SOCK 01;35 # socket
DOOR 01;35 # door
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file
SETUID 37;41 # file that is setuid (u+s)
SETGID 30;43 # file that is setgid (g+s)
CAPABILITY 30;41 # file with capability
STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
# This is for files with execute permission:
EXEC 01;32
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
# If you use DOS-style suffixes, you may want to uncomment the following:
#.cmd 01;32 # executables (bright green)
#.exe 01;32
#.com 01;32
#.btm 01;32
#.bat 01;32
# Or if you want to colorize scripts even if they do not have the
# executable bit actually set.
#.sh 01;32
#.csh 01;32
# archives or compressed (bright red)
.tar 01;31
.tgz 01;31
.arj 01;31
.taz 01;31
.lzh 01;31
.lzma 01;31
.tlz 01;31
.txz 01;31
.zip 01;31
.ZIP 01;31
.z 01;31
.Z 01;31
.dz 01;31
.gz 01;31
.lz 01;31
.xz 01;31
.bz2 01;31
.bz 01;31
.tbz 01;31
.tbz2 01;31
.tz 01;31
.deb 01;31
.rpm 01;31
.jar 01;31
.rar 01;31
.ace 01;31
.zoo 01;31
.cpio 01;31
.7z 01;31
.rz 01;31
# image formats
.jpg 01;35
.JPG 01;35
.jpeg 01;35
.JPEG 01;35
.gif 01;35
.GIF 01;35
.bmp 01;35
.BMP 01;35
.pbm 01;35
.pgm 01;35
.ppm 01;35
.tga 01;35
.xbm 01;35
.xpm 01;35
.tif 01;35
.tiff 01;35
.TIF 01;35
.TIFF 01;35
.png 01;35
.PNG 01;35
.svg 01;35
.svgz 01;35
.mng 01;35
.pcx 01;35
.mov 01;35
.MOV 01;35
.mpg 01;35
.mpeg 01;35
.m2v 01;35
.mkv 01;35
.ogm 01;35
.mp4 01;35
.m4v 01;35
.mp4v 01;35
.vob 01;35
.qt 01;35
.nuv 01;35
.wmv 01;35
.asf 01;35
.rm 01;35
.rmvb 01;35
.flc 01;35
.avi 01;35
.AVI 01;35
.fli 01;35
.flv 01;35
.swf 01;35
.gl 01;35
.dl 01;35
.xcf 01;35
.xwd 01;35
.yuv 01;35
.cgm 01;35
.emf 01;35
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
.axv 01;35
.anx 01;35
.ogv 01;35
.ogx 01;35
# audio formats
.aac 00;36
.au 00;36
.flac 00;36
.mid 00;36
.midi 00;36
.mka 00;36
.mp3 00;36
.MP3 00;36
.mpc 00;36
.ogg 00;36
.ra 00;36
.wav 00;36
.WAV 00;36
.wma 00;36
.m4a 00;36
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
.axa 00;36
.oga 00;36
.spx 00;36
.xspf 00;36


text:
Q: join 2 datatable with and condition caluse LINQ hi guy i have 2 datatable like this
dt1
id (1,2,3)
name (abc,xyz,def)
num(11,12,13)

dt2
id (1,2,3)
name (abc,xyz,def)
num_from (10,13,11)
num_to   (14,14,14)

how could i select id which have num between num_from and num_to using linq
i tried this
dtres = (from t1 in dt1.AsEnumerable()
        join t2 in dt1.AsEnumerable() on t1.Field<string>("ID") equals t2.Field<string>("ID")
                         where t1["num"]>= t2["num_from"]  &&
                         t1["num"]<= t2["num_to"]
                         select t1).CopyToDataTable();

A: Consider the following code:
It produce the result as IEnumerable<AnonymousType>, not DataRow, so cannot apply CopyToDataTable() extension method, instead I have provided a custom extension method at the bottom of this code ToDataTable, you can change the number of columns from the final result, I have included everything.
My understanding from your question is you need a filter such that Num in DataTable1 is between Num_From and Num_To in the Datatable2
 var resultDataTable =
    dt1.AsEnumerable().Join(dt2.AsEnumerable(), t1 => t1["id"], t2 => t2["id"], (t1, t2) => new { t1, t2})
                      .Where(t => (int.Parse(t.t2["num_from"].ToString()) <= int.Parse(t.t1["num"].ToString()) && int.Parse(t.t2["num_to"].ToString()) >= int.Parse(t.t1["num"].ToString())))
                      .Select(t => new {
                                                     Id1 = t.t1["id"].ToString(),
                                                     Name1 = t.t1["name"].ToString(),
                                                     Num1 = t.t1["num"].ToString(),
                                                     Id2 = t.t2["id"].ToString(),
                                                     Name2 = t.t2["name"].ToString(),
                                                     Num_From = t.t2["num_from"].ToString(),
                                                     Num_To = t.t2["num_to"].ToString()
                                        }
                             ).ToList().ToDataTable();

Extension method to convert IEnumerable to DataTable
public static class ExtensionDT
{
    public static DataTable ToDataTable<T>(this List<T> items)
    {
        var tb = new DataTable(typeof(T).Name);

        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in props)
        {
            tb.Columns.Add(prop.Name, prop.PropertyType);
        }

        foreach (var item in items)
        {
            var values = new object[props.Length];
            for (var i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }

            tb.Rows.Add(values);
        }

        return tb;
    }
}

A: Creating a join operation on Linq database is not possible like we do on Mysql and sql. But you can create a simple function to help you do that. You will need a function to return a string or interger for you:
   private ObservableCollection<Var_Items> _var_ItemsList;
        public ObservableCollection<Var_Items> Var_ItemsList
        { get { return _var_ItemsList; }
        set { _var_ItemsList = value;
              NotifyPropertyChanged("Var_ItemsList");
        }
       }

    dtres = from t1 in dt1.AsEnumerable() where t1["num"]>= getMyVar1(t1["num"]) and t1["num"]<= getMyVar1(t1["num"]) select t1;

        public string getMyVar1(int find_var)
        {
            var thisvar = from t2 in dt2.AsEnumerable() where t2["num_from"] >= find_var select t2;
            varitems = new ObservableCollection<Var_Items>(Var_ItemsList);
            return varitems.Last();
        }

        public string getMyVar2(int find_var)
        {
            var thisvar = from t2 in dt2.AsEnumerable() where t2["num_to"] >= find_var select t2;
            varitems = new ObservableCollection<Var_Items>(Var_ItemsList);
            return varitems.Last();
        }

I have tried to simplify my answer to be easier to understand. I hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to delete added value in cells in Excel Worksheet
From the picture on the left side, it is the input and after the user presses the button the output will appear on the right side.
My problem is that after the user presses the button and the result appears. I want the inputted data on the left side to disappear so that the user can re-input the data again and again
What do I need to add in my code so that it will give the result I want.
This is my code:
Private Sub CommandButton1_Click()
Dim i As Long, j As Long
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")

Set AddNew = wks.Range("M65356").End(xlUp).Offset(5, 0)

For i = 1 To 15
    For j = 1 To 7
        AddNew.Cells(i, j) = wks.Range("B1").Cells(i, j)
    Next j
Next i

End Sub

A: Just add :
wks.Range("B1").Cells(i, j) = ""

After your AddNew line

A: Your current code skips over the last inputline (15). But maybe consider to not use loops but to transfer the data in one go:
Private Sub CommandButton1_Click()

Dim wks As Worksheet: Set wks = Worksheets("Sheet1")
Dim AddNew As Range: Set AddNew = wks.Range("M65356").End(xlUp).Offset(5, 0)

AddNew.Resize(16, 7).Value = wks.Range("B1:H16").Value
wks.Range("B1:H16").Value = ""

End Sub


text:
Q: Как увеличить шрифт текста при клике на кнопку на чистом js Имеется счетчик, при клике на кнопку увеличивается число, нужно что бы еще увеличивался размер шрифта при каждом клике, вопрос что не так и как поправить

window.onload = initializer;
var  theCount = 0;
function initializer() {
    document.getElementById("incremenButon").onclick = increaseCount;
    document.getElementById("incremenButon").addEventListener('click',changeSize);
}
function increaseCount() {
    theCount++;
    document.getElementById("currentCount").innerHTML = theCount;
}

function changeSize (e) {
    document.getElementById("currentCount").style.fontSize = theCount;
}

        Щелкние на кнопке

        Текущее зачение: 0

    <button id="incremenButon">
        Инкрементировать счетчик
    </button>

A: fontSize укажите в пикселях (em, rem), в чем надо, тогда заработает, например
document.getElementById("currentCount").style.fontSize = theCount + 'px'

A: Можно так

var  theCount = 0;
document.getElementById("incremenButon").addEventListener('click',changeSize);

function changeSize (e) {
    theCount++;
    document.getElementById("currentCount").innerHTML = theCount;
    document.getElementById("currentCount").setAttribute('style', `font-size: ${theCount}pt`);

}

        Щелкние на кнопке

        Текущее зачение: 0

    <button id="incremenButon">
        Инкрементировать счетчик
    </button>


text:
Q: The perm argument in the permutedims Julia I can't fully understand how this argument affects the functionality of the permutedims function. I read the official doc for this function many times:

permutedims(A::AbstractArray, perm)
Permute the dimensions of array A. perm is a vector or a tuple of length ndims(A) specifying the permutation.

The first point that comes bold to me is that the perm can be a Tuple or a Vector of length ndims(A). So if the A is a 3D Array, then length(perm)==3 and so on. But, I can't understand how the permutation part takes place.
Then, Let's consider a similar example to what they brought in the doc:
julia> A = reshape(Vector(1:18), (3,2,3))
3×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  4
 2  5
 3  6

[:, :, 2] =
 7  10
 8  11
 9  12

[:, :, 3] =
 13  16
 14  17
 15  18

julia> permutedims(A, (3, 2, 1))
3×2×3 Array{Int64, 3}:
[:, :, 1] =
  1   4
  7  10
 13  16

[:, :, 2] =
  2   5
  8  11
 14  17

[:, :, 3] =
  3   6
  9  12
 15  18

Since the above script is a little bit long in visualization, and hard to follow, I provided the results beside each other in the following picture:

I can see, for example, the first element of each A's inner Matrix comes in the first column of each inner matrix of permutedims's result. But I can't understand how the perm=(3, 2, 1) is doing that! How should I interpret the values of the perm argument (here, (3, 2, 1))? And, for me it gets much harder to figure it out when I try another example of A with different ndims and size! I asked for an explanation about the perm here, But I couldn't understand it either. So I decided to ask about it as a stand-alone question.

A: I think it's easier to see from the size than by looking at the printout. Making sure no two dimensions have the same size for clarity:
julia> x = rand(10, 20, 3, 4);

julia> permutedims(x, (1,2,4,3)) |> size  # exchange 3rd & 4th
(10, 20, 4, 3)

julia> invperm((1,2,4,3)) == (1,2,4,3)    # easy case, self-inverse
true

julia> y = permutedims(x, (4,1,2,3));     # move the 4th dim to be 1st

julia> size(y)
(4, 10, 20, 3)

julia> y[:, 7, 13, 2] == x[7, 13, 2, :]
true

julia> invperm((4,1,2,3))
(2, 3, 4, 1)

julia> permutedims(x, (2,3,4,1)) |> size  # put the 1st dim last
(20, 3, 4, 10)

For the 3D example above:
julia> A = reshape(1:18, (3, 2, 3));

julia> B = permutedims(A, (3, 2, 1));  # reverse order of dims

julia> A[1,1,:] == B[:,1,1]  # these are the red circles
true

julia> A[2,1,:] == B[:,1,2]  # these are the yellow circles
true

A: Since the official implementation of permutedims is quite optimized. It is sometimes instructive to rewrite an impelementation to mimic it for educational purposes. So here is one which might clear things a bit hopefully (though @mcabbott's answer is just as good and less cumbersome):
function toy_permutedims(M, perm)
    # verify proper input
    !isperm(perm) && error("perm must be perm. duh!")
    length(perm) == ndims(M) || error("perm must be of size ndims")

    # calculate new shape of output array
    newshape = [size(M, i) for i in perm]
    # output array is same number of elements...
    Mout = similar(M)
    # but different shape...
    Mout = reshape(Mout, newshape...)

    # go over all input elements (1,1,1),(2,1,1)...
    for I in CartesianIndices(M)
        # The crucial bit: permute indices into new array!
        Mout[(I[perm[i]] for i = 1:ndims(M))...] = M[I]
    end
    # phew! all done
    return Mout
end

The implementation recovers the result in the OP:
julia> toy_permutedims(A, (3,2,1))
3×2×3 Array{Int64, 3}:
[:, :, 1] =
  1   4
  7  10
 13  16

[:, :, 2] =
  2   5
  8  11
 14  17

[:, :, 3] =
  3   6
  9  12
 15  18

But perhaps the comments are helpful. Also debugging statements can be sprinkled more easily.
See other answer too.

A: Try to visualize that example as a cube made of various slices.
The rows are the first dimension, the columns are the second one and the depth of the cube, made by going across the various slices, is the third dimension.
Then it becomes clear that in that example the perm argument should be interpreted as "put in the new first dimension (columns) what was originally in the 3rd dimension (e.g. the "depth" vector 1,7,13), put in the new second dimension (rows) what was originally in the second dimension, put in the new 3rd dimension what was originally in the first dimension (e.g. the column vector 1,2,3 that now goes across the various slices)". A perspective of what I said on the same matrix you named A:

Basically, you put in the perm parameter the desired newly ordered list of the old dimensions.


text:
Q: Reading a binary file and using new line as a delimiter to create binary chunks I am totally out of my element when it comes to binary files. I need to read a binary file and break it into chunks using new line as the delimiter. I have tried googling this but its come up empty. Any help on this would be appreciated. It Has to be opened as binary file.
So i have a file of unknown encoding. I need to break out the file by chunks using \n newline as my delimiter. I am looking for a function that can break out this binary data with the new line as the delimiter.

A: Helper Method
class MyEnumerableExtensions
{
    //For a source containing N delimiters, returns exactly N+1 lists
    public static IEnumerable<List<T>> SplitOn(
        this IEnumerable<T> source,
        T delimiter)
    {
        var list = new List<T>();
        foreach (var item in source)
        {
            if (delimiter.Equals(item))
            {
                yield return list;
                list = new List<T>();
            }
            else
            {
                list.Add(item);
            }
        }
        yield return list;
    }
}

Usage

I need to read a binary file and break it into chunks using new line as the delimiter.

var path = "binary-file.bin";
var delimiter = (byte)'\n';
var chunks = File.ReadAllBytes(path)
    .SplitOn(delimiter)
    .ToList();

A: First of all, if there is mixed binary and text data in your file and you don't know how to unpack it you're in trouble.
Second of all, what exactly do you mean by 'newline'? Were these newlines specifically written into the binary file as 0x10? Or were you using some .Net interface that had a method like WriteLine on it? Or maybe you wrote some text into this file that contained newlines? In that case what encoding was used?
If you were handwriting these newlines as 0x10 you should be able to figure out how to split your binary stream on a single byte without too much difficulty.
If you used WriteLine or similar, that means it actually wrote Environment.NewLine not just 0x10. In most cases on windows computers that means you are looking for 0x1310. If you do not also trim the 0x13 off the front you will have an extra garbage byte at the end of every segment.
Now if you were writing strings with specific encoding that means that a newline is actually 0x10 or 0x00010 or 0x00000010 and Environment.NewLine is 0x1310 or 0x00130010 or 0x0000001300000010 so you should be splitting on those values instead. Oh and endian-ness would flip all these...

A: Streams are inherently byte oriented. You can read a byte at a time into a buffer until you hit a newline, and then make a new buffer to read into.

A: First of all you have to verify what do you mean by new line - it could be: \n, \n\r or \r\n.
When you're sure of your notion of newline you should read binary file bytes and check if the bytes sequence contains byte equivalents of the characters I've mentioned above.
For example if you have single byte you may check it as follows:
byte singleByte = 1; //this value will be read from stream
if (singleByte == (byte) '\n')
{
    //your code goes here
}


text: Q: Tracing with xfig to make shapepar command I'd like to create text/character shaped paragraphs similar to this. I've followed its reference and have been able to make simple shaped paragraphs with it, but I am unable to hand-trace any character (like $e$ or $\gamma$) to any reasonable degree. One of the comments on the reference mentions AutoTrace but that program crashes on any input, even -help. I've also found an online site that can trace and output to a fig file, but all I get is a whole lot of unconnected points and no closed polygon shape. How can I trace/outline a shape (not by hand) in either xfig or elsewhere to make a polygon shape in xfig to then generate a \shapepar command?


text:
Q: Heaps in c++ using vectors How does lastline work?
Will it make max heap or min heap?
int myints[] = {10,20,30,5,15};

std::vector<int> v(myints,myints+5);

std::make_heap (v.begin(),v.end());

A: std::make_heap is part of the "heap" functions in the standard library. They all work by using an underlying data store. In the case you gave you are using a std::vector as your data store.
Calling std::make_heap passing in the range of your data store will heapify its contents, causing the first element to the largest in value and satisfying all requirements for std::push_heap and std::pop_head.

How does lastline work ? will it make max heap or min heap?

It makes a max heap within the std::vector supplied (v).


text:
Q: How to navigate from an ActionSheet action to another view? I have an ActionSheet and I don't know how to make navigation to another view from the action sheet callback button.
let action = ActionSheet.Button.cancel {
     //navigation???
}
ActionSheet(title: Text("some title"), buttons: [action])

I.E: I would like to have this as a chooser when selecting images from different sources: camera or camera roll.

A: This is how you can achieve this:
struct ContentView: View {
    @State var isSheet: Bool = false
    @State var isPresented: Bool = false

    var body: some View {
        NavigationView {
            Button(dict.description) {
                self.isSheet = true
            }.actionSheet(isPresented: $isSheet) {
                ActionSheet(title: Text("Some title"), message: nil, buttons: [
                    .default(Text("Present view")) {
                        self.isPresented = true
                    },
                    .cancel()
                ])
            }
            .navigationBarTitle(Text("Home"))
            .sheet(isPresented: $isPresented, content: { Text("This is another view!") })
        }
    }
}

Instead of .sheet, you can also use .popover


text:
Q: Adding views to an activity programmatically I have this code on the onCreate() of an Activity that is inside a Tab:
String[] info = getResources().getStringArray(R.array.fc_1);
TextView q = new TextView(this);
q.setText(info[0]);

TextView a1 = new TextView(this);
a1.setText(info[1]);

TextView a2 = new TextView(this);
a2.setText(info[2]);

TextView a3 = new TextView(this);
a3.setText(info[3]);

LinearLayout linlay = new LinearLayout(this);
linlay.addView(q);
linlay.addView(a1);
linlay.addView(a2);
linlay.addView(a3);
setContentView(linlay);

What happens is that only the first textview gets shown, with the correct value of info[0], but the others textviews just aren't there.
Any ideas what I might be doing wrong?

A: Default orientation of LinearLayout is horizontal. So the other TextViews are to the right of the first which takes all the space. Change the orientation of the LinearLayout to vertical.

A: The standard height and width of the LinearLayout is fill_parent. That makes your first textView to use all the space hiding the rest of the views (putting them outside of the screen).
You can either change the orientation of linlay to be vertical, or change the width of the different textviews. You will need to play with LinearLayout.LayoutParams to achieve this.

A: String[] info = getResources().getStringArray(R.array.fc_1);

TextView q = new TextView(this);
q.setText(info[0]);
TextView a1 = new TextView(this);
a1.setText(info[1]);

TextView a2 = new TextView(this);
a2.setText(info[2]);

TextView a3 = new TextView(this);
a3.setText(info[3]);

LinearLayout linlay = new LinearLayout(this);
linlay.setOrientation(1);//set vertical orientation
linlay.addView(q);
linlay.addView(a1);
linlay.addView(a2);
linlay.addView(a3);
setContentView(linlay);

try this code block


text:
Q: Actionscript 3 rotate object to mouse Hello i watched tut on youtube and i wrote this code to make object rotate to mouse position, but it kinda doesnt work correctly.
code:
package  {

import flash.display.MovieClip;
import flash.events.Event;

public class char extends MovieClip
{
    private var _pointer = this;

    public function char()
    {
        addEventListener(Event.ENTER_FRAME, onEnter);
    }

    private function onEnter(event:Event):void
    {
        //Initialize dx and dy variables
        var dx:Number = mouseX - _pointer.x;
        var dy:Number = mouseY - _pointer.y;

        //Store angle in angle variable
        var angle:Number = Math.atan2(dy, dx) * 180 / Math.PI;

        //Apply angle
        _pointer.rotation = angle;
    }
}

}

A: You need to take mouseX and mouseY coordinates from the parent movie clip because:

*

*_pointer.x and _pointer.y are also expressed in the parent's coordinate system

*Rotation of a movie will interfere with mouseX and mouseY values (they will reflect the non-rotated object)

So you need to modify these two lines:
var dx:Number = parent.mouseX-_pointer.x;
var dy:Number = parent.mouseY-_pointer.y;


text:
Q: Fixing my macro to copy a range to the next blank column? I need to copy a cell range into the next blank column in a separate sheet, every time the forms buttons for the macro is clicked.
Here's the code. The problem is it copies to the next blank row, and I need the next blank column. I have tried editing the line* in various ways and end up with errors, or no effect (e.g. replacing "Rows" with "Columns").

*

*Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

If found the base for the 'copy to next blank row VBA' here at SO, at the following link:
Copy and Paste a set range in the next empty row
Thanks for any help, I'm stuck currently.
Sub TestCopyToDB()

    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("sheet1")
    Set pasteSheet = Worksheets("sheet2")

    copySheet.Range("M1:M15").Copy
    pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub

A: The Cells method has two arguments, row and column, i.e.,
Cells(1,1)   '<~~ equivalent to cell "A1"
Cells(1,3)   '<~~ equivalent to cell "C1"
Cells(10,13) '<~~ equivalent to cell "M10"

The Offset method works similarly, with two arguments, row_offset, and column_offset, so:
.Offset(1,1)   '<~~ returns the cell one row below, and one column to the right
.Offset(-1, 3) '<~~ returns the cell one row above, and 3 columns to the right

Making some adjustments, and change the .End(xlUp) (for rows) to .End(xlToLeft), gives this:
With pasteSheet
    .Cells(1, .Columns.Count).End(xlToLeft).Offset(0,1).PasteSpecial _
        Paste:=xlPasteValues, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
End With


text:
Q: How do you clear buffer result in Speech Recognizer? I'm trying to write a speech recognizer that will have the ability to be cleared after some duration (like two seconds) without switching it off.
private func startRecording() throws {

    recognitionTask?.cancel()
    self.recognitionTask = nil

    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)
    try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    let inputNode = audioEngine.inputNode

    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
    guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") }
    recognitionRequest.shouldReportPartialResults = true

    // Keep speech recognition data on device
    if #available(iOS 13, *) {
        recognitionRequest.requiresOnDeviceRecognition = false
    }

    recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in
        var isFinal = false

        if let result = result {
            self.textView.text = result.bestTranscription.formattedString

            // MARK: here after 2 seconds my recognition should clear it's own result in string

            isFinal = result.isFinal
            print("Text \(result.bestTranscription.formattedString)")
        }

        if error != nil || isFinal {
            self.audioEngine.stop()
            inputNode.removeTap(onBus: 0)

            self.recognitionRequest = nil
            self.recognitionTask = nil

            self.recordButton.isEnabled = true
            self.recordButton.setTitle("Start Recording", for: [])
        }
    }
    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
        self.recognitionRequest?.append(buffer)
    }

    audioEngine.prepare()
    try audioEngine.start()

    textView.text = "(Go ahead, I'm listening)"
}

I can not rebuild speech recognition. It should be working constantly.
I tried to do the following, but afterwards my microphone turns off:
inputNode.removeTap(onBus: 0)
audioEngine.inputNode.removeTap(onBus: 0)


text:
Q: Arithmetic progressions in the set $\{ \lfloor n\pi \rfloor, n \in \mathbb{N}\}$
Prove that the set $\{ \lfloor n\pi \rfloor, n \in \mathbb{N}\}$
  contains an arithmetic progression with $m$ elements for any integer $m\ge 3$.

I did a few terms. The set starts with
$$0, 3, 6, 9, 12, 15, 18, 21, \color{red}{25}, 28, 31,34,37,40,43,\color{red}{47},50,53,\\56,59,62,65,\color{red}{69},72,75,78,81,84,87,\color{red}{91},94,97,100,103,...$$
and so on. For $m\le 8$ the first $8$ elements are an arithmetic progression with common difference $3$.
For $m> 8$, the numbers with red are where the difference with the previous term is $4$ and they happen every 7th term (I guess because $7\pi \approx 22$). But $7 \pi < 22$, so from a certain point on this pattern won't be respected anymore. Does this help in any way?

A: There's an easy way separate from the path you're looking at. The easy way is to just note that, for every real number $r$ we have
$$\inf_{n\in\mathbb N}\{nr\}=0$$
where $\{\cdot\}$ is the fractional part of a number. This fact isn't too hard to prove from scratch, though I won't reproduce a proof here. Then, you can just find some $n$ such that $n\pi = k + \alpha$ where $k\in \mathbb Z$ and $\alpha < 1/m$. Then the floors of $0n\pi,\,1n\pi,\,2n\pi,\ldots,(m-1)n\pi$ are just $0,\,k,\,2k,\ldots,(m-1)k$, which is an arithmetic progression.
Though I'm not sure of a way to use it to solve this particular problem, your observation does connect into deep observations with continued fractions, which can be used to describe the way that the whole sequence $\lfloor n\pi\rfloor$ looks to follow a simple pattern over short periods (e.g. "increases by 3 each step" or "increases by 3 each step, except every seventh step where it increases by 4" and then describing that the "every seventh step" is actually changing between "seven" and "eight" steps somewhat regularly - but the period at which this happens isn't quite constant either). It's a bit much to explain in the compass of an answer, but the patterns you're noticing have some interesting consequences.


text:
Q: How to make a reset button AR Core examples in Unity? Hi i am actually newbie in Unity development and making my first project in AR i just wanted to ask how to make a reset button in "Hello ARCore" example i know how to add buttons in canvas just wanted to know the function in script to be used. Any help appreciated

A: Use this unity reference: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html
An example would be:
using UnityEngine.SceneManagement;
    public class something : MonoBehaviour
    {
        private void restart()
        {
            SceneManager.LoadScene("YOUR_SCENE_NAME");
        }
    }

It is pretty self-explanatory, but if you need some more help (or a more in depth explanation) I am happy to help you out.


text:
Q: How to select columns where value is not zero How do you select columns where the value is not zero?
If I have 3 columns
column1|column2|column3
-------+-------+-------
   0   |   50  |   99

I want the query to show only columns that have values > 0
so that the result will be
column2|column3
-------+-------
   50  |   99

I have tried this:
SELECT * FROM `table1` WHERE `column1` != '0'

A: Would a json string containing the columns work for your purposes?
SELECT CONCAT(COALESCE(CASE WHEN column1 > 0 THEN JSON_OBJECT('column1', column1) END, ''),
              COALESCE(CASE WHEN column2 > 0 THEN JSON_OBJECT('column2', column2) END, ''),
              COALESCE(CASE WHEN column3 > 0 THEN JSON_OBJECT('column3', column3) END, '')
             )
FROM table1;

This will return a json string only containing the columns that are > 0. So using your example this would return {"column2": 50}{"column3": 99}

A: SQL returns tables of data.  Tables have the same columns on every row.  You cannot have a query where a column is missing in a row.
So if this select statement:
select column1, column2, column3 from table1

returns
column1 | column2 | column3
    1   |    20   |   50
    0   |    12   |    2
    3   |    15   |    0
   10   |     0   |   11

what do you expect would be in the first column of the second row if we omit columns with zeros?
The best you can do is replace zeros with NULL.
select CASE WHEN column1 > 0 THEN column1 ELSE NULL END,
       CASE WHEN column2 > 0 THEN column2 ELSE NULL END,
       CASE WHEN column3 > 0 THEN column3 ELSE NULL END
from table1

Which would give us this:
column1 | column2 | column3
    1   |    20   |   50
  NULL  |    12   |    2
    3   |    15   |  NULL
   10   |   NULL  |   11


text:
Q: Querying for documents that have missing / undefined fields in Watson Discovery Service We have a set of JSON documents loaded into Watson Discovery Service. Some have a field (say X) for example X: MyXValue and some don't have that field at all.
Can I write a query in WDS language that will return all documents in the collection that are missing the X field?
Thanks,
Eldad

A: Not sure about your question but I think that you can try to use the query and the filter parameter.
filter
An unranked query language search for matching documents.
Example: filter=bees
You can also check my link above to try another parameters that can be really useful for your queries with WDS.

*

*Check the Official Query reference from Watson Discovery Service.

A: No, you can't write that query. The query operators are documented at
https://console.bluemix.net/docs/services/discovery/query-operators.html#query-operators
You might think that you could use the "does not include" operator with a wildcard (X:!*), but that doesn't return any results.
If possible you should add an attribute to your documents so that you can test an attribute that is present, rather than trying to detect the absence of an attribute.


text:
Q: Why am i getting Input Mismatch Error (Java) So far i have this.
  import java.util.*;
  public class Moviesol{
  public static void main (String[] args){
    Scanner sc= new Scanner(System.in);
    Movie[] m = new Movie[3];
    for(int i=0;i<3;i++){
        String name =sc.nextLine();

        String company =sc.nextLine();

        String genre =sc.nextLine();

        Long budget =sc.nextLong();
        m[i] = new Movie(name, company, genre, budget);
    }

    String ip = sc.nextLine();

    MovieByGenre(m , ip);

}
public static void MovieByGenre(Movie[] m, String ip ){
    for(int i=0;i<3;i++){
        if(((m[i].getgenre()).equals(ip))&& (m[i].getbudget()>=80000000)){

                System.out.println("High Budget Movie");}
        else if(((m[i].getgenre()).equals(ip))&& (m[i].getbudget()<=80000000)){
                System.out.println("Low Budget Movie");
        }
    }
}
}

This is the other class
class Movie {
private String name;
private String company;
private String genre;
private Long budget;
public Movie(String name, String company, String genre, Long budget){
    this.name=name;
    this.company=company;
    this.genre=genre;
    this.budget=budget;
}
public String getgenre(){
    return genre;
}
public Long getbudget(){
    return budget;
        }
}

I am using getter methods to grab info from other class. The program takes
'name' of String type
'Company' of string type
'genre' of string type
'budget' of long type.
i need to match genre with the 'ip' String, if it matches, budget is compared , and prints accordingly
My input
asd
asd
asd asd
90000000000
asd
asd
asd asd
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextLong(Scanner.java:2373)
at java.base/java.util.Scanner.nextLong(Scanner.java:2328)
at Moviesol.main(Moviesol.java:13)

Please help!!!

A: The exception means that the input read from the file does not fir into the object you want to store it. For example scanner.nextInt() thows that exception if the next element is "abcd".
Your related code is:
        String name =sc.nextLine();
        String company =sc.nextLine();
        String genre =sc.nextLine();
        Long budget =sc.nextLong();

So for each movie you have to enter 3 lines of text and one long integer number.
asd asd is only one line, and surely not a number.

A: import java.util.*;
public class Moviesol{
public static void main (String[] args){
Scanner sc= new Scanner(System.in);
Movie[] m = new Movie[3];
for(int i=0;i<3;i++){
    String name =sc.nextLine();

    String company =sc.nextLine();

    String genre =sc.nextLine();

    String strBudget =sc.nextLine();
    Long budget = null;
    try {
        budget = Long.parseLong(strBudget);
    } catch (NumberFormatException ex) {
        // what happens if they didn't enter a number
    }
    m[i] = new Movie(name, company, genre, budget);
}

String ip = sc.nextLine();

MovieByGenre(m , ip);

}


text:
Q: Is there something analogue to LVM logical volumes in BTRFS? I like the way BTRFS does snapshots and subvolumes but it does not feel right to use LVM just because I want my logical volume to be of certain size.
Is there something analogue to LVM logical volumes in BTRFS? The closest thing to it seems to me to be the BTRFS subvolumes.
I am not reluctant to have BTRFS on top of LVM just because I want this. I am asking because if BTRFS does not have this functionality I will continue using LVM for the time being...

A: Btrfs subvolumes are not block devices, and thus don't have a fixed size. Why do you want to make it a specific size? Your question is analogous to asking "Is there a way to make a folder of specific size?" It will be the size of the contents, and you can't make it bigger or smaller short of adding or removing data from the subvolume.
If you want to limit a user from putting too much data on it, then enable a quota for the subvolume, which will cap it at a specified size.

A:
Problem is that I want to limit (group of) users to specific amount of data on the subvolume without messing with quotas, etc. - At the moment I just give them access to a LVM logical volume, and all works well. Maybe I am thinking about using a wrong BTRFS feature as I am not a BTRFS expert... I will rephrase the question and remove "subvolume" from it.

I believe you are overengineering this.
I'm not completely familiar with Btrfs, but I believe I am familiar enough with ZFS from which Btrfs has drawn much inspiration to make heads and tails of this.
In both, you work with a blob of storage, which is subdivided into file systems which can have various properties set. For example, quotas for the file system. Btrfs calls this "subvolumes".
Just make a subvolume, set the quota to however much you want it to be possible to grow to (similar to your LVM logical volume size), then if everything is set up to support quotas in Btrfs do something like btrfs qgroup limit 1G <path>/<subvolume>. See the btrfs Wiki Use Cases page on implementing quotas for some more details on what to do if that doesn't work out immediately.


text:
Q: wcf Username and password security with basichttpBinding--Message Based I have created an interface with ServiceContract on interface and OperationContract on all its methods. I implemented this interface in a class and then in my asp.net website i added wcf service which created an svc file (because i wanted to host it in IIS with my website). Now the service is up and accessible at http://localhost:8732/webui/webservice/camservice.svc. Now i want to enable username and password authentication for this service. I suppose svc uses basicHttpBinding because i didn't have to make any configurations in my web.config to make it run. Now how can i enable username/password authentication on this service? There are lot of articles on internet but, i believe, wcf security is such a giant that i can't get a focused explanation on username/password authentication with the method i have used. I am using .net 4.0 with vs 2010
Edit: Ok, i have narrowed the problem down a little bit. I believe, message level security is what i need like
<security mode="Message">
                <message clientCredentialType="Certificate" />
            </security>

I could have gone for SSL but for that, i will have to go to db for each service call and authenticate the user. what i prefer is that a client with valid certificate is served by the service. I got a lot of information from this article. What it does not explain is how to setup x509 certificate on client and server and how can i control that only my clients can acquire valid certificate.

A: If you want to achieve username password validation without SSL you can use something called a ClearUsernameBinding that allows you to transport username/password over http.
NOTE: Do use this only when your service is behind a company firewall that gives enough security to your server that hosts your service.
In terms of using 2 way SSL you need to install the service certificate .pfx on your server which has been issued by a trusted authority or  self signed certificate under Personal store folder of Local Machine account.
Then for client certificates you need to request the client to send a .cer file and install it on your servers under Trusted People store folder on the local machine account.
On the client machine you need to install the client certificate .pfx under Personal store folder of Current User.
NOTE: When using self signed certificate on your server then your client which performs a call to your webservice via code needs to have the below code which is to bypass the security exception that comes up for self signed certificates:
    System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) =>
                                                                             {
                                                                                return true;
                                                                             };


text:
Q: How to get domain extension from URL with jQuery? I'm trying to get domain extension from a URL with jQuery. But not sure how to cover all possible scenarios. Highlighted the parts I need to get from the URL;
https://www.amazon.**com**/dp/067144901X
https://www.amazon.**co.uk**/dp/067144901X
https://www.amazon.**it**/dp/067144901X
https://www.amazon.**de**/dp/067144901X

$(".get").on('click', function(event) {
  var DomainEX = $('#url').val();
  alert(DomainEX);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="url">
<button class="get">GET</button>

A: You can convert to URL, get the host name:
const hostName = (new URL('https://www.amazon.com/dp/067144901X')).hostname;
Then extract everything that is after the site name:
const extension = hostName.split('amazon').pop()

//https://www.amazon.com/dp/067144901X
//https://www.amazon.co.uk/dp/067144901X

function getDomainExtension(url, siteName) {

  const hostName = (new URL(url)).hostname;
  const extension = hostName.split(siteName).pop()
  console.log(hostName)

  return extension;
}

$(".get").on('click', function(event) {
  var DomainEX = $('#url').val();
  const extension = getDomainExtension(DomainEX, 'amazon')
  console.log(extension)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="url">
<button class="get">GET</button>

A: Usually to extract parts from an URL the URL API might come handy. In your case the url.hostname but this returns all the parts of a domain (including subdomain and extension).
For your specific case you could use a bit of regex:

const getAmazonExt = url => /amazon.([^/]+)/.exec(url)[1];

console.log(getAmazonExt('https://www.amazon.com/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.co.uk/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.it/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.de/dp/067144901X'))


text:
Q: How to increase a value from populated field in struts 2? Hi Good Morning to All!
I have one problem. I am developing a web application by using struts 2. I am doing paginating. i.e. 10 records per page. Here i need two links one is "Previous" and another one is "Next". Here i have populated the bean values like this two as ,
For Previous link as,
<c:if test="${currentPage != 1}">

   <s:url id="previous" action="retrieve">
    <s:param name="condopurchaselistbean.currentPage">${currentPage-1}</s:param>
   </s:url>
   <s:a href="%{previous}" >Previous</s:a>

</c:if>

For Next link as,
<c:if test="${currentPage lt noOfPages}">

   <s:url id="next" action="retrieve">
     <s:param name="condopurchaselistbean.currentPage">${currentPage+1}</s:param>
   </s:url>
    <s:a href="%{next}" >Next</s:a>

</c:if>

But its not working. Below is the exception i am getting :
javax.servlet.ServletException: java.lang.NoSuchFieldError: deferredExpression
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:157)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:374)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
com.visionraices.interceptors.MyLoggingInterceptor.intercept(MyLoggingInterceptor.java:64)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)

I dont know. What is my mistakes.
Anybody can help me?
Thanks in advance...

A: Please have a look at tablesorter jquery plugin.
Or you can use limit and offset at your backend databse query for each click of next or previous.(You are making a call to database each time you click on next or previous.)

A: You could have multiple libraries of JSTL on your classpath (webapp + app server for example).
For this guy with your same error it worked: random error. "javax.servlet.ServletException: java.lang.NoSuchFieldError: deferredExpression"

Not related to your problem, but why are you using JSTL IFs instead of Struts2 IFs ??
You could easily change <c:if test="${currentPage lt noOfPages}"> to <s:if test="%{currentPage < noOfPages}"> or even <s:if test="currentPage < noOfPages">, and it would be better. Actually, with S2 you don't need JSTL anymore.


text:
Q: Django property field calculated from other property fields Does anyone know a way in Django to calculate a field from the values of other property fields? Here's my invoice model:
class Invoice(models.Model):
    types = [
        ('customer', 'Customer'),
        ('supplier', 'Supplier')
    ]

    number = models.CharField(max_length=30)
    date_invoice = models.DateTimeField('Date', default=timezone.now())
    comment = models.TextField(default=get_default_invoice_comment())
    type = models.CharField(max_length=20, choices=types, default='customer')
    partner_id = models.ForeignKey(
        'Partner', default=1, on_delete=models.CASCADE)
    currency_id = models.ForeignKey(
        'Currency', default=1, on_delete=models.CASCADE)

    @property
    def tax_amount(self):
        total = 0
        for line in self.invoiceline_set.all():
            total += line.tax_amount
        return total

    @property
    def subtotal(self):
        total = 0.0
        for line in self.invoiceline_set.all():
            total += line.subtotal
        return total

    @property
    def total(self):
        return self.subtotal + self.tax_amount

    def __unicode__(self):
        return self.number

The tax_amount and subtotal on the InvoiceLine model are property fields. The subtotal gets calculated fine, however the total does not as it depends on another property field (tax_amount, which also does not get calculated properly) and I guess Django does not know in what order to perform the calculations? To reiterate, the problem is the total and tax_amount fields are always empty (even if the fields they are calculated from are not).

A: The problem was that some invoice_lines did not have a tax_id (because they were added before that was implemented) and the tax_amount field on the InvoiceLine is a property field that is calculated by the rate on the related Tax object. So the tax_amount on those lines wasn't able to be computed as it tried to sum floats and None types.


text:
Q: Using for or while loops Every month, 4 or 5 text files are created.  The data in the files is pulled into MS Access and used in a mailmerge.
Each file contains a header.  This is an example:
HEADER|0000000130|0000527350|0000171250|0000058000|0000756600|0000814753|0000819455|100106
The 2nd field is the number of records contained in the file (excluding the header line).  The last field is the date in the form yymmdd.
Using gawk (for Windows), I've done ok with rearranging/modifying the data and writing it all out to a new file for importing into Access except for the following.
I'm trying to create a unique ID number for each record. The ID number has the form 1mmddyyXXXX, where XXXX is a number, padded with leading zeros. Using the header above, the first record in the output file would get the ID number 10106100001 and the last record would get the ID 10106100130.
I've tried putting the second field in the header into a variable, rearranging the last header field into the required date format and then looping with "for" statements to append the XXXX part of the ID and then outputting it all with printf but so far I've been complete rubbish at it.
Thanks for your help!
gary

A: Invoke awk(1) with the option "-F |" and use the following statement to set the identifier:
    id=sprintf("1%02d%02d%02d%04d", substr($9,3,2), substr($9,5,2), substr($9,1,2), NR)


text:
Q: HttpContext.Connection.RemoteIpAddress returns private address for asp.net core in kubernetes I have an asp.net core 7.0 api application in a docker container hosted in Kubernetes behind an Nginx ingress controller.
To get the client ip address i'm using

context.HttpContext.Connection.RemoteIpAddress

for all user requests I get a Private Ip address like '10.244.0.1'
In such instances i'm expecting Public IP address

A: You need to configure nginx to forward the X-Forwarded-For and X-Forwarded-Proto headers. Example:
server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

Then setup the UseForwardedHeaders middleware. This middleware will update HttpContext.Connection.RemoteIpAddress using the X-Forwarded-For header value.
var builder = WebApplication.CreateBuilder(args);

// ...
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

var app = builder.Build();

app.UseForwardedHeaders();

// ...

Check: Configure ASP.NET Core to work with proxy servers and load balancers


text:
Q: Exploratory Structural Equation Model (ESEM) in R: Exploratory Specification Model Thanks in advance for your help.  I have been trying to developed ESEM in R, and am hoping to generate some fit statistics for a 3 factor model.  My data include 12 items and 213 observations.  I pasted the data below the codes/output.  Does anyone know how to specify the model?  I got as far as this by referring to Using SEM Library in R software to Analyze Exploratory Structural Equation Models which is a free/open access pdf on the web at http://www.statistics.gov.hk/wsc/CPS105-P6-S.pdf
> R.esem1 <- data[,1:12]
> R.Exp11 <- factanal(R.esem1, factors=3)
> R.Exp11

Call:
factanal(x = R.esem1, factors = 3)

Uniquenesses:
V1    V2    V3    V4    V5    V6    V7    V8    V9   V10   V11   V12
0.494 0.461 0.364 0.580 0.543 0.301 0.454 0.290 0.476 0.350 0.691 0.415

Loadings:
Factor1 Factor2 Factor3
V1   0.669  -0.237
V2  -0.173   0.703   0.125
V3  -0.165   0.763   0.162
V4   0.646
V5   0.629          -0.228
V6   0.810          -0.204
V7   0.693  -0.201  -0.162
V8   0.780  -0.319
V9  -0.153   0.115   0.698
V10  0.795  -0.130
V11          0.353   0.429
V12  0.754  -0.130

                 Factor1 Factor2 Factor3
SS loadings      4.288   1.456   0.838
Proportion Var   0.357   0.121   0.070
Cumulative Var   0.357   0.479   0.548

Test of the hypothesis that 3 factors are sufficient.
The chi square statistic is 70.89 on 33 degrees of freedom.
The p-value is 0.00014
> F <- matrix(R.Exp11$loadings[1:36],12,3)
> F
         [,1]        [,2]         [,3]
[1,]  0.66932977 -0.23709108 -0.045363582
[2,] -0.17343046  0.70255656  0.124827678
[3,] -0.16488945  0.76301805  0.162456136
[4,]  0.64649603  0.01476361 -0.039659133
[5,]  0.62943270 -0.09518228 -0.228036660
[6,]  0.81009704 -0.03544650 -0.203655807
[7,]  0.69264229 -0.20104671 -0.161732725
[8,]  0.77994820 -0.31877158  0.007721083
[9,] -0.15341745  0.11504193  0.697808969
[10,]  0.79530262 -0.13044749 -0.030411798
[11,] -0.01535601  0.35274568  0.429080759
[12,]  0.75359352 -0.12964507 -0.020748897
> F1 <- rbind(F[1,], F[3,], F[9,])
> F1
       [,1]       [,2]        [,3]
[1,]  0.6693298 -0.2370911 -0.04536358
[2,] -0.1648894  0.7630180  0.16245614
[3,] -0.1534174  0.1150419  0.69780897
> H <- solve(F1) %*% diag (sqrt(diag(F1 %*% t(F1))))
> Rotated.F <- zapsmall (F %*% H)
> Rotated.F
        [,1]       [,2]       [,3]
[1,]  0.7115282  0.0000000  0.0000000
[2,] -0.0302663  0.7280160 -0.0263732
[3,]  0.0000000  0.7973563  0.0000000
[4,]  0.7373234  0.2807600 -0.0517021
[5,]  0.6542020  0.1662707 -0.2283677
[6,]  0.8792445  0.3052633 -0.2175721
[7,]  0.7200541  0.0627940 -0.1333875
[8,]  0.8338454 -0.0551906  0.0748016
[9,]  0.0000000  0.0000000  0.7236774
[10,]  0.8811011  0.1720919 -0.0096444
[11,]  0.1476431  0.3570187  0.3793123
[12,]  0.8354451  0.1552792  0.0009104
> solve(H) %*% t(solve(H))
       [,1]       [,2]       [,3]
[1,]  1.0000000 -0.5263845 -0.3138709
[2,] -0.5263845  1.0000000  0.3924230
[3,] -0.3138709  0.3924230  1.0000000
> Model.esem1<-specifyModel()
1: F1-> Y1,1am11,.8
2: F1-> Y2,1am41,.7
3: F1-> Y3,1am51,.7
4: F1-> Y4,1am61,.9
5: F1-> Y8,1am71,.7
6: F1-> Y9,1am81,.8
7: F1-> Y10,1am101,.9
8: F1-> Y11,1am111,.1
9: F1-> Y12,1am121,.8
10: F2-> Y2,1am22,.7
11: F2-> Y3,1am32,.8
12: F2-> Y4,1am42,.3
13: F2-> Y5,1am52,.2
14: F2-> Y6,1am62,.3
15: F2-> Y7,1am72,.1
16: F2-> Y8,1am82,.1
17: F2-> Y10,1am102,.2
18: F2-> Y11,1am112,.4
19: F2-> Y12,1am122,.2
20: F3-> Y4,1am43,.1
21: F3-> Y5,1am53,.2
22: F3-> Y6,1am63,.2
23: F3-> Y7,1am73,.1
24: F3-> Y8,1am83,.1
25: F3-> Y9,1am93,.7
26: F3-> Y11,1am113,.4
27: F4-> X,1am133,0
28: F4-> Y1,NA,0
29: F4-> Y2,NA,0
30: F4-> Y3,NA,0
31: F4-> Y4,NA,0
32: F4-> Y5,NA,0
33: F4-> Y6,NA,0
34: F4-> Y7,NA,0
35: F4-> Y8,NA,0
36: F4-> Y9,NA,0
37: F4-> Y10,NA,0
38: F4-> Y11,NA,0
39: F4-> Y12,NA,0
40: F4-> X,1am134,1
41: F1<->F2,NA,.5
42: F1<->F3,NA,.3
43: F2<->F3,NA,.4
44: F1<->F1,NA,1
45: F2<->F2,NA,1
46: F3<->F3,NA,1
47: F4<->F1,NA,1
48: F4<->F2,NA,1
49: F4<->F3,NA,1
50: F4<->F4,NA,1
51: F1<-F4,NA,.5
52: F2<-F4,NA,.5
53: F3<-F4,NA,1
54:
Read 53 records
NOTE: it is generally simpler to use specifyEquations() or cfa()
  see ?specifyEquations
NOTE: adding 13 variances to the model
> sem.esem1 <- sem(Model.esem1,R.esem1,N=213)
Error in `colnames<-`(`*tmp*`, value = obs.variables) :
'names' attribute [213] must be the same length as the vector [12]

1   4   3   1   3   1   2   3   1   1   3   2
4   2   3   4   5   4   3   5   2   4   2   5
5   1   1   4   4   5   5   5   1   5   4   5
5   1   1   5   5   5   5   5   1   5   5   5
5   1   1   5   5   4   5   3   1   5   1   5
4   3   4   3   3   1   1   2   3   2   1   2
3   4   1   1   2   1   1   3   2   3   1   1
3   3   4   3   3   3   3   3   1   4   2   3
5   1   1   1   5   4   5   4   1   4   1   4
3   1   2   3   4   3   1   4   3   5   1   5
5   1   1   3   3   5   5   5   1   5   1   5
2   5   5   2   1   5   2   1   5   3   4   5
5   5   5   3   4   4   5   4   3   5   4   5
5   3   5   4   5   5   3   3   1   5   3   5
5   1   1   3   1   3   3   5   3   3   1   5
5   3   1   4   5   5   3   2   2   2   1   3
5   1   1   4   5   4   5   5   5   5   1   5
5   2   1   1   5   5   5   5   1   5   1   5
2   1   1   5   5   5   5   5   1   5   5   5
5   1   2   5   5   5   4   5   1   5   1   5
3   3   1   3   3   2   3   3   2   3   2   4
5   1   1   3   4   4   4   4   1   5   1   4
3   1   1   1   3   1   1   1   4   3   1   1
5   1   1   1   5   4   5   4   1   4   1   4
5   1   1   3   3   3   3   5   1   5   1   5
1   2   5   1   1   1   1   1   5   1   3   1
4   1   1   3   3   3   4   4   3   3   2   4
4   2   1   3   2   3   4   2   4   3   2   3
2   3   4   1   1   1   1   1   1   2   1   4
3   5   5   1   1   1   2   1   5   1   5   2
5   1   4   3   3   1   1   3   3   5   3   3
4   2   4   3   3   4   4   5   3   3   2   4
1   2   3   1   2   4   4   4   1   5   3   5
3   4   4   3   4   4   5   4   3   4   2   3
4   1   4   3   4   4   1   3   2   1   4   3
5   1   3   5   5   3   5   5   3   5   1   5
5   1   1   1   1   3   5   5   5   3   5   5
5   1   1   3   3   3   3   3   3   3   1   3
4   4   4   4   4   5   3   1   3   3   3   4
4   3   1   5   4   5   5   5   1   5   1   5
1   3   3   3   3   4   4   3   4   5   1   4
5   1   5   3   3   3   2   3   5   5   5   5
3   5   5   2   5   3   1   2   1   5   1   2
5   1   2   5   5   3   5   5   1   5   1   5
4   4   1   4   2   3   4   4   3   4   2   4
4   3   4   4   4   5   1   4   1   3   3   4
3   3   3   4   2   3   2   3   5   5   3   4
3   2   3   2   3   3   4   3   2   2   2   3
4   1   1   4   4   5   5   5   3   5   3   5
4   2   2   2   4   4   4   4   3   4   3   4
3   2   2   3   2   1   2   3   2   2   1   2
1   1   1   1   4   1   1   1   1   1   1   1
5   2   1   4   5   5   2   5   2   2   5   5
3   5   5   4   5   3   1   2   3   4   3   4
5   3   1   5   5   5   5   5   3   5   1   3
5   2   3   3   4   4   5   5   2   5   5   5
4   2   1   4   3   3   3   5   3   3   1   4
5   1   1   5   5   5   3   4   1   5   1   5
5   3   5   3   3   3   3   3   4   2   3   1
1   2   4   5   4   3   1   2   5   5   4   5
5   1   1   3   5   5   5   5   3   5   5   5
5   3   3   5   5   5   1   5   5   5   5   5
3   1   1   3   3   3   3   5   1   4   1   4
3   1   1   3   5   5   5   5   1   5   1   5
3   5   5   1   1   1   2   1   5   1   5   2
5   1   1   5   5   5   5   5   3   5   2   5
4   2   1   2   2   1   1   3   4   1   1   4
4   5   5   3   5   5   5   4   1   5   2   5
4   1   1   4   4   1   1   4   3   4   1   4
4   1   1   1   4   5   5   3   1   1   1   3
4   1   3   5   3   4   4   4   1   4   1   4
5   2   2   3   3   4   3   3   3   4   3   4
3   3   4   2   5   4   1   2   1   2   2   2
4   2   3   3   3   2   2   3   3   4   2   4
5   1   2   4   5   4   3   5   4   3   2   5
5   1   1   3   5   5   5   5   5   5   1   5
5   1   1   1   1   5   5   5   1   5   3   5
5   1   1   5   5   5   5   5   1   5   1   5
5   2   2   5   5   3   2   5   1   5   1   5
3   2   3   3   1   2   1   1   1   1   1   1
4   5   1   1   1   5   4   1   3   5   1   5
5   2   2   5   4   5   5   4   1   5   1   4
3   3   4   2   5   4   1   2   1   2   2   2
5   2   2   4   5   5   5   5   3   5   2   5
5   3   4   4   5   5   5   5   4   5   1   5
4   1   2   2   2   4   4   3   5   5   3   3
3   2   3   3   1   2   2   3   2   3   2   2
4   3   3   3   5   3   2   3   3   2   2   4
5   2   2   4   5   3   3   4   1   3   2   3
5   2   1   4   5   4   5   4   1   5   1   4
4   3   3   2   3   4   4   3   2   3   3   4
3   1   1   1   3   3   2   2   1   1   1   3
5   1   1   5   5   5   5   5   5   5   1   5
5   1   1   1   5   5   5   5   1   5   1   5
5   3   3   1   5   5   5   4   3   5   3   5
5   1   1   5   0   5   5   3   3   3   3   3
3   5   5   1   5   5   5   4   5   3   5   5
5   5   4   5   5   5   5   5   5   5   5   4
5   3   1   2   5   5   5   5   1   5   1   5
5   1   1   5   5   5   5   4   2   5   2   5
5   1   3   4   3   3   4   4   3   5   2   5
2   1   2   1   3   2   4   2   4   3   3   2
4   2   3   2   3   4   3   4   2   4   2   4
5   3   1   4   5   5   5   5   1   5   1   4
4   1   1   1   4   4   4   4   3   3   3   3
4   1   1   2   4   4   4   4   1   5   2   4
5   3   3   5   5   5   1   5   5   5   5   5
5   1   1   3   3   5   5   5   1   5   1   5
5   1   1   4   4   4   3   4   3   4   2   3
4   3   3   4   3   3   3   4   3   4   3   3
5   5   5   5   5   5   3   3   1   5   5   3
5   1   3   4   3   4   4   4   2   5   1   5
5   3   1   3   2   3   2   3   3   3   3   3
4   3   4   5   5   5   4   5   2   5   1   5
5   3   4   5   5   5   5   5   1   5   1   5
5   1   1   4   4   3   4   5   4   5   3   5
5   1   1   2   4   4   4   4   1   5   1   5
3   3   2   4   1   3   1   4   2   4   1   2
5   1   1   1   3   5   1   5   1   5   1   5
3   1   1   3   3   3   5   3   1   5   1   3
4   1   1   1   5   5   5   5   1   5   1   5
5   3   2   3   3   4   4   3   4   4   5   5
5   3   2   5   5   5   5   1   1   5   1   5
5   3   5   4   3   5   4   3   1   2   1   4
5   1   1   5   5   5   5   5   1   5   1   5
3   1   1   1   1   1   1   2   2   2   3   3
5   1   1   5   5   4   4   5   1   5   1   5
3   2   5   1   2   1   1   2   4   2   3   5
5   1   1   5   5   4   4   5   5   5   3   4
5   1   1   3   5   5   5   5   1   5   1   5
5   1   4   5   3   5   2   5   3   5   5   5
2   4   3   2   1   2   2   3   4   2   2   4
4   4   2   3   3   5   2   4   4   4   2   5
5   1   1   3   3   3   3   3   2   3   1   4
3   1   1   3   4   3   3   3   3   3   3   5
5   5   1   5   5   5   5   5   5   5   3   5
5   4   3   2   3   3   1   4   4   2   2   5
3   1   1   3   3   4   4   4   1   5   1   4
3   2   1   2   4   5   5   3   1   5   1   5
3   4   3   1   1   3   1   3   1   4   2   5
4   1   3   4   4   3   4   5   2   5   1   5
5   1   1   3   5   5   3   5   1   5   3   5
5   2   2   2   3   4   4   3   2   5   1   5
4   3   1   3   3   3   3   4   3   3   1   4
5   1   1   1   4   2   1   3   3   4   1   3
2   5   2   1   1   1   1   1   5   1   1   1
5   3   4   4   4   4   1   5   3   5   3   5
2   5   4   1   1   2   3   4   4   5   5   1
4   5   5   4   4   3   2   2   4   5   2   3
4   1   1   1   4   1   1   1   1   1   1   5
1   3   1   1   2   3   1   2   5   3   3   1
5   2   5   5   5   5   5   5   2   5   3   5
3   2   3   2   2   2   2   3   3   2   2   2
5   3   2   3   2   4   5   5   4   4   1   3
2   4   5   2   2   2   2   2   1   1   1   1
1   3   4   1   1   1   1   1   5   1   4   3
5   1   1   4   5   5   3   5   1   5   1   5
4   1   1   5   5   5   5   5   1   5   1   5
1   5   5   2   1   1   1   1   2   1   1   3
5   1   1   5   5   5   5   5   1   5   1   5
4   3   3   4   3   4   4   4   3   3   3   3
4   3   1   1   4   4   4   4   1   4   4   4
2   3   4   1   1   1   1   1   5   1   4   1
3   3   2   4   4   4   4   4   2   4   4   3
4   2   3   4   4   4   5   4   3   4   3   4
5   2   4   4   4   5   5   4   2   5   3   5
3   3   1   3   3   5   4   4   3   5   2   5
3   2   5   4   3   3   4   5   3   5   1   5
1   5   5   1   1   1   1   1   1   1   5   1
4   5   5   5   3   4   5   5   2   5   3   5
5   5   5   3   3   3   3   3   3   4   1   3
1   5   5   1   4   3   2   2   5   3   1   3
4   5   5   5   4   5   3   4   2   5   4   5
3   1   5   3   4   2   1   2   2   2   3   2
5   5   5   5   5   5   5   5   2   5   3   5
1   3   5   3   3   3   1   2   3   5   3   5
4   5   5   3   2   4   4   3   2   4   2   5
4   2   4   3   3   4   2   3   4   4   2   3
4   2   3   2   3   4   5   4   3   4   5   4
5   2   2   1   3   3   3   4   4   5   1   4
3   5   1   3   3   5   5   5   3   5   3   5
4   1   1   2   3   4   4   4   1   4   1   5
5   1   2   5   5   5   5   5   1   5   1   4
1   3   4   1   1   1   1   1   5   1   4   3
3   2   2   3   2   1   1   3   2   5   5   3
5   1   1   5   5   4   5   5   1   5   1   5
5   5   4   3   5   5   5   5   1   5   1   5
3   4   4   1   1   4   4   2   2   3   4   3
5   3   4   4   1   4   3   2   3   4   3   5
2   5   5   1   5   1   1   1   1   1   1   1
4   3   4   3   4   3   1   4   5   5   5   5
3   4   4   1   1   2   1   1   3   2   5   2
5   2   1   5   5   5   5   4   1   5   1   5
5   1   3   5   5   5   5   5   2   5   2   5
4   4   5   3   4   2   1   2   4   2   4   3
2   1   4   1   2   3   4   5   3   2   4   5
3   2   3   4   4   4   4   3   3   4   3   4
4   4   4   3   3   2   3   3   3   3   4   4
5   3   1   5   5   4   5   5   4   5   5   5
3   4   1   1   3   1   1   4   5   2   2   1
2   5   1   1   1   4   1   2   2   1   5   3
1   1   2   2   3   2   2   2   2   3   1   4
5   1   2   3   5   5   3   5   3   5   3   5
5   2   2   5   5   5   5   5   1   5   1   5
3   2   1   2   4   3   3   5   4   3   2   3
5   5   5   5   4   4   4   5   1   4   5   5
5   5   5   3   3   2   3   4   5   4   2   5
5   1   1   5   5   5   5   5   5   5   1   5
5   2   4   1   4   1   5   5   5   5   1   2
2   3   4   3   3   3   3   2   3   2   3   4
3   5   4   1   2   2   2   2   2   2   1   1
3   3   3   2   3   1   1   1   5   1   3   1
2   3   4   2   1   1   2   1   2   3   5   1


text:
Q: t-stat for feature selection I want to calculate  t-Statistic for feature selection in R with for loop. Data has 155 columns and dependent variable is binary (mutagen - nonmutagen). I would like to assign a t-stat for every columns. The problem is I couldn't figure out how can I write it.
Here is the formula I'm trying to implement in R:

Also I wrote a code but I'm not sure about it and it's just for first column. I need to write it in for loop for all columns.
abs(diff(tapply(train_df[,1], train_df$Activity, mean))) / sqrt(sd((train_df$NEG_01_NEG[train_df$Activity == "mutagen"])^2) / (length(train_df$NEG_01_NEG[train_df$Activity == "mutagen"])) +
   sd((train_df$NEG_01_NEG[train_df$Activity != "mutagen"])^2) / (length(train_df$NEG_01_NEG[train_df$Activity != "mutagen"])))

Thanks in advance!

A: If you don't want to worry about speed (and with 155 columns you probably don't care) you can use the t.test function and apply it to every column.
Simulate some data first
set.seed(1)
DF <- data.frame(y=rep(1:2, 50), x1=rnorm(100), x2=rnorm(100), x3=rnorm(100))
head(DF)

  y         x1          x2         x3
1 1 -0.6264538 -0.62036668  0.4094018
2 2  0.1836433  0.04211587  1.6888733
3 1 -0.8356286 -0.91092165  1.5865884
4 2  1.5952808  0.15802877 -0.3309078
5 1  0.3295078 -0.65458464 -2.2852355
6 2 -0.8204684  1.76728727  2.4976616

Then we can apply the t.test function to all but the first column using the formula argument.
group <- DF$y
lapply(DF[,-1], function(x) { t.test(x ~ group)$statistic })

which returns the test statistic for each column.
t.test computes a lot of extra information that you don't need so you can speed this up substantially by doing the computations directly, but it really isn't necessary here


text:
Q: Multi-leveled data, how to model? I am designing biochemical analyses of human brain samples. In a nutshell, we believe levels of some things are related to levels of other things that relate to levels of other things that relate to the donor's diagnosis. Rather than try to describe everything badly, here is a diagram of our model to examine:

The green "Diag." is our outcome (diagnosis). It will be binomial (diseased/not), ordinal (not < not.path < mild < diseased), multinomial (not, not.variant, mild, diseased), or ordinal with 30 possible levels (a clinical scale--essentially can be treated as numeric). Everything else is to be directly measured by appropriate assays. Part of our model is that there is a feedback effect of Fe levels. By the way, this is a simplified version, since "Tau prot" also participates in specific localization of sAPPa but does not influence its levels. Fe3 influences aggregation of ptau, which can influence levels of tau by acting as a tau sink. Again, ignoring such complexities for now. The model here is to only reflect levels of the materials, not aggregation or cellular compartmentalization--that would be a later model to tackle.
More information: From prior experiments, we should expect many of the variables to violate assumption of normality. There may be violation of assumption of independence for all of the variables in the first column, especially since there may be feedback between IL1beta and IRP1 (at the very least). We will be testing the covariants of age, sex, and APOE genotype, all of which are known important covariates for this disorder.
So, what is the nuts-and-bolts recommendation on how to analyze this? I am already familiar with SEM, but does SEM handle the "retrograde" Fe connections? How does one deal with violations of normality or independence?
We would like to also deal with collection from different centers as a random variable, making it a multi-level model. If we are fortunate enough to get samples from multiple brain regions from all the same subjects, we'd also like to treat that effect as a random variable (individual subject).
Thank you.

A: Since you mention feedback I would suggest you view your system as evolving in time, namely a time series. In this case I would at least consider Sugihara's S-map and CCM methods and forget about the final diagnosis for a while. The advantage of these methods is that they are specifically aimed at data arising from dynamical systems. CCM tells you which variables are causative to your higher level observables (ptau, A$\beta$, sAPP$\alpha$), while S-map allows you to predict them. You might find out that many of the variables you measure are actually redundant. The downside is, of course, that you need to collect time-series data. If you want to test whether or not such methods are useful for said data, you need only collect time series of the observables mentioned earlier and see if they admit a low dimensional attractor ("have low embedding dimension"). This is done using the Simplex method - take a look at the first pages of this tutorial for the R package rEDM.


text:
Q: How to get Cross Browser Compatibilty for window.fileReader API of HTML5 Hi Html5 developers and HTML4 developers too...
I want to know whether is there any way to support window.fileReader API of html5 in IE8 and above.
the code below :
if(window.fileReader){
  alert("supported"); // in html5 works and fires alert but not in IE8
}

Actually, i want to read the contents of file before submitting.

*

*Can i use some condition, if window.fileReader is supported then
follow 'A' line of code using HTML5 , else if window.fileReader is not supported then
use some other thing...to read the file

*I also want to know the way to read the file contents without using
HTML5 fileAPI... but not using ActiveXObject.

Waiting for the response..

A: There are multiple pieces that you'll need to check the support of:
//Full File API support.
if ( window.FileReader && window.File && window.FileList && window.Blob )
{
    //Supported
}

else alert( "Not supported" );

Your second requirement:

I also want to know the way to read the file contents without using
  HTML5 fileAPI... but not using ActiveXObject.

What you could do is this:

*

*Have an iframe (you'll be posting to this)

*Have an input of type "file"

*When the user selects the local file, you use javascript to post it to the iframe (e.g. document.getElementById( "myForm" ).target = "myIframe"; document.getElementById( "myForm" ).submit();

*The iframe's POSTed page (Could be PHP) reads the uploaded file contents and does a callback to the parent page (e.g. <script>window.parent.someCallbackFunction( theFileCOntents );</script>)

A: You can check features with simple if logic and wrap your functionality there.
if ('FileReader' in window) {
  // Do something with FileReader since it's supported
} else {
  // Do something with your polyfill solution
}

You can try a polyfill solutions like this one (works in IE8):
https://github.com/Jahdrien/FileReader

A: You can always use a try-catch to check the FileReader() is supported in a browser.
try {
    var reader = new FileReader();
    //do something
}
catch(e) {
    alert("Error: seems File API is not supported on your browser");
    //do something
}


text:
Q: Validate user input of character and iterate how many times character exists in sentence The while loop and for loop works individually, but combining them does no generate the desired output.
I want the user to enter a sentence, and then a character. The Character must be entered as a single 1 character, if not then the program should ask again.
sentence = input("Type sentence: ")
sentence = sentence.lower()
singleCharacter = input("Type character: ")

char = 0

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
    for i in sentence:
        if i == singleCharacter:
            char += 1

print(singleCharacter,"appears",char,"times in your sentence")

A: Something like:
sentence = input("Type sentence: ")
sentence = sentence.lower()
singleCharacter = input("Type character: ")

char = 0

while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')

print(sum([1 for c in sentence if c == singleCharacter]))

Should do what you want.

A: The problem you encounter in this block of code:
while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
    for i in sentence:
        if i == singleCharacter:
            char += 1

It will only give you the desired output when you enter more than one character at first time, otherwise it will not enter for loop for counting the number of characters which inside of while loop condition len(singleCharacter) != 1 and then will return the initial characters count 0. Therefore to work as expected you should put for loop for counting the characters outside while loop:
while len(singleCharacter) != 1:
    singleCharacter = input('Enter a single character: ')
for i in sentence:
    if i == singleCharacter:
        char += 1

Output:
Type sentence: Hello World!
Type character: l
l appears 3 times in your sentence

A: Just get for-loop out of while loop and it will be working fine


text:
Q: assistance using update method in php with mysql I have a simple option tag in html which lists all users held on the database when the user clicks donate i want to take the value entered and update the dontate_Total row relvant to that user with the value entered by the user in the donate label section.
here is my html

    <form>

User:

    <select>
    <?php do{?>
    <option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
    <?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
    </select>

Donation £	<input type="text" maxlength="9" value="0.00"/>

<input id="submit" type="submit" value="DONATE" />

    </form>

the above works fine but now I want to run and update query when the user hits the DONATE input field. here is my sql statment which I believe wont work just after some advice
$donate_sql =UPDATE `donate` SET donate_Total=  donate_Total + $_GET['value'] WHERE first_Name = 'first_Name'   AND last_Name ='last_Name';

thanks

A: How are you?
Edited (more profound) answer:
In your HTML, you have to give names to your fields in order to retrieve them from your PHP script i.e. give your <select> element a name (attribute), like this:
<select name="fullname">

Also, the nested <option> elements should have a "value" attribute, this is because you almost always want the identification of a field to be a unique ID (so there's no mistake when refering to a table row) but you want to show useful information to the user, such as a full name.
If you plan on using an ID, then your code (in HTML) should be updated to:
<option value="<?php echo $rsNames['id']; ?>"> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>

This will be outputed as:
<option value="1">John Doe</option>
<option value="2">Jane Doe</option>

Then in your PHP file, it would be much easier to write a query that updates exactly the user that you want.
<?php

$id = $_GET['fullname'];
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + {$_GET['value']} WHERE id = $id";
mysql_query($donate_sql);

?>

If you don't plan on using an ID, you have to face the fact that if 2 users are called John Doe, you'll be updating the "total" amount of donation for both of them, and it's going to be a bit more complicated for you to parse the information.
Say you DON'T want to use an ID and you want to stick with your first and last name, then you would write something like:
<option value="<?php echo $rsNames['first_Name'] . '||' . $rsNames['last_Name'];?>"><?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>

Which would produce an output similar to:
<option value="John||Doe">John Doe</option>
<option value="Jane||Doe">Jane Doe</option>
<option value="Mary Jane||Doe">Mary Jane Doe</option>

The third <option> tag is an example of why you can't rely on spaces to parse first and last name; a person can have double name or double last name -- or both, as it is in my case ;-)
The separator || is an arbitrary one, the idea is to use one or more characters that are not likely going to be used as part of the name or the last name.
This approach (which again, is a really bad one) would require you to parse the first name and last name individually afterwards, so your script would end up being:
<?php

$name = $_GET['fullname']; //'fullname' is the name of our <select>
$name = explode('||',$name); //this returns an array, with each position defined by the || token

//$name is now an array(0=>'John',1=>'Doe') - for example.

//Get the first name
$firstName = $name[0]; //John

//Get the last name
$lastName = $name[1]; //Doe

//Finally, your SQL would be updated to be:
$donate_sql = "UPDATE `donate` SET donate_Total= donate_Total + {$_GET['value']} WHERE first_Name = '$firstName' AND last_Name ='$lastName'";

mysql_query($donate_sql);
?>

Old answer
The quick answer is:
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + {$_GET['value']} WHERE first_Name = 'first_Name' AND last_Name ='last_Name'";

And then using the mysql_query($donate_sql); function.
However as @hjpotter92 pointed out, you should (amongst other things) add an ID column to that table and set it as a primary key.
Also, you should keep in mind things like escaping values that come in your requests ($_POST and $_GET), so no SQL injection is applied to your query.
Hope this helps!
Cheers.

A: Instead of directly using mysql_query function, try building the mysql statements, like $donate_sql built here by fsodano and then using an echo $donate_sql; to check, and then using the statement on a backup table. I prefer to do it this way, then messing up with the original work.
On a side note, your form consists of 'ALL' the first and last name combinations(I guess!), so there won't be any unique value for $_GET['first_name']
Do give the following statement a consideration!
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + {$_GET['value']} WHERE first_Name = '{$_GET['first_Name']}' AND last_Name = '{$_GET['last_Name']}'";
echo $donate_sql;

A: <?php
//code at the top of the document
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
    $donation = mysql_real_escape_string($_POST['donation']);
    $fname = mysql_real_escape_string($_POST['first_name']);
    $lname = mysql_real_escape_string($_POST['last_name']);
    $donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname'";
}

?>

    <form method="POST" accept-charset="utf-8">

User:

    <select>
    <?php do{?>
    <option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
    <?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
    </select>

Donation £	<input name="donation" type="text" maxlength="9" value="0.00"/>

<input id="submit" type="submit" value="DONATE" />

    </form>

A: $value = mysql_real_escape_string($_GET['value']);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + {$value}

adds a small layer of security to your query, but however give credit to @fsodano this is just an add on to his answer


text:
Q: Appendix on multiple pages: add the title "(Continued)" I have realized a Latex document that holds two appendices. They are both included as .tex files.
The first appendix, APPENDIX A, is one page long (and it is fine).
The second, APPENDIX B, is several pages long and I need on each of the pages after the first one to insert a title stating: APPENDIX B (Continued).
Unfortunately, Latex only puts the APPENDIX B title on the first page of this second appendix but on the remaining ones there is no title.
I have tried to play with the \appendix command but I couldn't figure out a viable solution. Do you have any idea?
Thank you in advance!
Paolo

A: I used the article class and faked the inclusion of the appendix sections/chapters by directly writting them into the main file. The second appendix got some label, which is referred to using the \fancyhead command from fancyhdr package. The definition of a apppages (appendix pages) style is quite useful here. Afterwards, the pagestyle is switched back to plain
\documentclass[twoside]{article}
\usepackage{fancyhdr}
\usepackage{blindtext}

\fancypagestyle{apppages}{%
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\fancyhead[LE,RO]{\appendixname~\ref{appendix::b} (continued)}
}

\begin{document}
\section{First section}
\blindtext[50]

\appendix
\section{First appendix}
\clearpage
\pagestyle{apppages}
\section{Second appendix} \label{appendix::b}
\blindtext[20]
\clearpage % Clear the page
\pagestyle{plain}
\section{Other appendix}
\blindtext[10]

\end{document}


text:
Q: UnhandledPromiseRejectionWarning: Callback was already called (Loopback remote method) I'm getting an error that says
(node:27301) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.

From what I understand about rejecting promises in await's and per the Mozilla description:

If the Promise is rejected, the await expression throws the rejected value.

I reject the error in the callback that's wrapped around my Promise like so:
Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      Airport.find({
        // code
      }, (err, results) => {
        if (err)
          reject(err) // Reject here
        else
          resolve(results)
      })
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }

My question is

*

*Why does it still consider my promise rejection unhandled? I thought the catch statement should silent this error.

*Why does it consider my callback already called? I have a return statement in my catch, so both should never be called.

A: The problem was actually my framework (LoopbackJS), not my function. Apparently at the time of writing this, using promises are not supported:
https://loopback.io/doc/en/lb3/Using-promises.html#setup
Meaning I can't even use await in my function because the remote method wraps my function somewhere else, so async would always be unhandled. I ended up going back to a Promise-based implementation of the inner code:
Airport.nearbyAirports = (location, cb) => {
const settings = Airport.dataSource.settings
const db = DB(settings)
let airports
NAME_OF_QUERY().then((res) => {
  cb(null, res)
}).catch((err) => {
  cb(err, null)
})

A: If Airport.find() throws an exception, then execution will jump to your catch block and your Promise will never be resolved or rejected. Perhaps you need to wrap it in its own try/catch:
Airport.nearbyAirports = async (location, cb) => {
  let airports
  try {
    airports = await new Promise((resolve, reject) => {
      try {
        Airport.find({
          // code
        }, (err, results) => {
          if (err)
            reject(err) // Reject here
          else
            resolve(results)
        })
      } catch (err) {
        reject(err) // Reject here too
        cb(err, null)
      }
    })
  } catch (err) { // Catch here
    cb(err, null)
    return
  }
  if (!airports.empty)
    cb(null, airports)
  }

A: As said here, loopback 3 support this by allowing you to use a simple return.
This :
Entry.findFooById = async (id, cb) => {
  const result = await Entry.findById(id);
  return result;
};

...Is equivalent to :
Entry.findFooById = (id, cb) => {
  Entry.findById(id)
    .then(result => cb(null, result))
    .catch(cb);
};

A: We use Loopback 2.31.0 and it also supports simple return for async functions used for remote methods. If you put a break-point somewhere in your remote method and jump one level above it in the call-stack you will see how it is implemented in loopback itself (shared-method.js):
  // invoke
  try {
    var retval = method.apply(scope, formattedArgs);
    if (retval && typeof retval.then === 'function') {
      return retval.then(
        function(args) {
          if (returns.length === 1) args = [args];
          var result = SharedMethod.toResult(returns, args);
          debug('- %s - promise result %j', sharedMethod.name, result);
          cb(null, result);
        },
        cb // error handler
      );
    }
    return retval;
  } catch (err) {
    debug('error caught during the invocation of %s', this.name);
    return cb(err);
  }
};

What it does here - it calls your function and if it is an async function - it will return a promise (retval.then === 'function' will be true). In this case loopback will handle your result correctly, as a promise. It also do the error check for you, so you no longer try/catch blocks in your code anymore.
So, in your own code you just need to use it like below:
Airport.nearbyAirports = async (location) => {
    let airports = await new Promise((resolve, reject) => {
        Airport.find({
            // code
        }, (err, results) => {
            if (err)
                reject(err) // Reject here
            else
                resolve(results)
        })
    });

    if (!airports.empty)
        return airports;
    }
    else  {
        return {}; // not sure what you would like to return here as it wan not handled in your sample...
    }
}

Note, you do not need to use callback (cb) at all here.


text:
Q: Contao CMS Query a 'checkboxWizard' BLOB field I have a question about how to query a 'checkboxWizard' BLOB field. In have added a such field to tl_member. This is working very fine. I can add "0 to N" selection to each members. Let's call this field "myBlob".
Now the questions is how to query "myBlob" with the Contao way? Let's say I want all member that are in the postal code "12120" and that have the id "2" of "myBlob" selected. Not only "2" but at least this one.
   $arrColumn[] = "tl_member.postal=?";
   $arrValues[] = 12120;

   $arrColumn[] = "tl_member.myBlob=?"; <- how to say "contains in the blob" here?
   $arrValues[] = 2;

   self::findBy($arrColumn, $arrValues)

A: The only way to do this (when using the default Contao method for such relationships) is to create a query like:
… WHERE myBlob LIKE '%"2"%'

So in your case it might be:
$arrColumn[] = "tl_member.myBlob LIKE ?";
$arrValues[] = '%"2"%';

However, this is of course cumbersome and might not work in all cases.
May be a better way would be to use codefog/contao-haste with its 'many to many' helper: https://github.com/codefog/contao-haste/blob/master/docs/Model/index.md
This way you will have a separate table containing the references.


text:
Q: How can Java remove leading whitespace? I have been trying to figure out why this Java code won't delete any leading whitespace to my actual string, I have been trying to use stripLeading() method and the trim(); method, and various other methods with the same functionality but still haven't gotten a favorable outcome. Code:
public static String message(String logLine) {
         logLine = (String) logLine.subSequence(logLine.indexOf(" ") + 1, logLine.length());
         return logLine;
         }
public static void main(String[] args) {

        System.out.println(message("[WARNING]:   \tTimezone not set  \r\n"));
    }

What results is what I wanted, just the words "Timezone not set" however I want this program to completely ignore leading whitespace, which for some reason it can't. Thank you for any help.

A: Possible solutions

*

*Use String::replaceFirst to keep only the part after a prefix ([WARNING]:) followed by whitespaces and the main part:
public static String message(String logLine) {
    return logLine.replaceFirst("^\\S*\\s+(\\S+(\\s+\\S+)*)\\s+$", "$1");
}

*As the prefix ends with ':', a solution offered in the comment using String::substring + String::trim works too:
public static String message(String logLine) {
    return logLine.substring(logLine.indexOf(":") + 1).trim();
}


text:
Q: How to enqueue a style using wp_enqueue_scripts()? I'm having difficult to load the path correctly in an 'enqueue' function.
What I am trying to achieve is to load a specific CSS stylesheet on a specific page...
The below works by adding the path to the markup on the correct template - but - the path is wrong...
 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
    if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', array(), '1.0.0', true );
      get_template_directory_uri() . '/css/flags.min.css',
    }
  }

The reason is because (I believe) the path is not set correctly to find the appropriate css folder...
The php is therefore missing this line:
get_template_directory_uri() . '/css/flags.min.css',

My question is - how do I add this line that locates the theme css folder? I tried the below but it did NOT work...
 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
   if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', array(), '1.0.0', true );
      get_template_directory_uri() . '/css/flags.min.css',
    }
   }

A: The second parameter of wp_enqueue_style() is an optional path.You are passing an empty array, which will enqueue nothing.
get_template_directory_uri() retrieves the current theme's root URI, which you can use in wp_enqueue_style():
 add_action('wp_enqueue_scripts','homepage');
  function homepage(){
   if ( is_page_template('page-home.php') ) {
      wp_enqueue_style('home-css', get_template_directory_uri() . '/css/flags.min.css', '1.0.0', true );
    }
   }

I mentioned "Optional", since there is also another way to use wp_enqueue_style. In this method, you can first use wp_register_style, and then enqueue it:
wp_register_style( 'home-css', get_template_directory_uri() . '/css/flags.min.css' );
wp_enqueue_style('home-css');

The same works for wp_enqueue_script().
Based on using parent theme or child, you might also want to take a look into get_stylesheet_directory_uri() too.


text:
Q: How to get my gridview updated without any postback once AjaxFileUpload completed I am using AjaxFileUpload in ASP.NET 4.0 website and I have one gridview to show the uploaded file list upon update.
I'm using AjaxFileUpload FileUploadComplete function to save uploaded file list & bind into my gridview. However, my problem is the gridview with databind doesn't showed up on the page instantly & it'll show only after postback.
Any one can advise how to trigger postback once file upload complete OR how to make my gridview updated without any postback?
Appreciate any suggestion. Thanks.

A: Maybe you can try placing the grid in an ajax updatepanel and adding the FileUpload control's FileUploadComplete event as a trigger to the panel. That way when the event is executed the grid's updatepanel will do its own postback and update the grid.