text:
Q: Encrypt tar.gz file on create I have a script which creates a nightly backup of several directories.
It is created using tar -czf, and the destination tar.gz file path is on a mounted network directory. The resulting file is about 1.2Gb large.
The network speed is reasonably fast (copying from the network drive to the local occurs at ~28MB/sec).
Now I want to use public-key encryption to encrypt the tar.gz file before transferring it to the network drive, and would like to know what the best way to do so is.
Should I create the file locally first, encrypt it, and then copy over?
Or is there a way to "stream" tar output through an encryption process, and write the results directly to the network drive?

A: Pack your_dir in a encrypted archive your_archive.tgz.gpg (symmetric encryption):
tar -cz your_dir | gpg -c -o your_archive.tgz.gpg

Unpack it:
gpg -d your_archive.tgz.gpg | tar xz

See the docs of GPG for how to use asymmetric instead of symmetric encryption.

A: The following process encrypts the file on local disk first, and can then be sent over the network (or stored however needed)

First, generate public and private keys (done only once):
openssl genrsa -out key.pem 2048
openssl rsa -in key.pem -out key-public.pem -outform PEM -pubout

Then, at each backup:

*

*Generate long random passphrase, save in file

*

*echo -n "Tl4R6dnvWXiDeXr1LtpCNkyLG1" > key.txt

*encrypt file with passphase

*

*openssl enc -aes-256-cbc -pass file:key.txt < UNENCRYPTED_FILE > encrypted.dat

*encrypt passphrase with public key

*

*openssl rsautl -encrypt -pubin -inkey key-public.pem < key.txt > enc.key.txt
Then save encrypted.dat AND enc.key.txt where desired.

To decrypt:

*

*Decrypt encrypted passphrase with private key

*

*openssl rsautl -decrypt -inkey key.pem < enc.key.txt > key.txt

*Decrypt file

*

*openssl enc -aes-256-cbc -d -pass file:key.txt < encrypted.dat > UNENCRYPTED_FILE

This is a lot longer than Florian's anwser, but I decided to use it so I can better understand the process, and not depend on server-dependent GPG configuration variables, etc. I also couldn't find any useful GPG documentation.

A: I do this with asymmetric key encryption. That means I have a public key (that I can share with anyone I'd like to send me encrypted packages) which allows me to encrypt the package. I also have a private key (that I do not share) which allows me to decrypt the package.
My commands to encrypt the current working directory: the -e to encrypt, the -r to specify a "recipient" or key to use, the -o to specify the output file.
$ tar -cvz . | gpg -e -r ABCD1234 -o backup.tgz.gpg

And to decrypt to the current working directory:
$ gpg -d backup.tgz.gpg | tar -xz

Or to decrypt to a standard tgz file for later unpacking:
$ gpg -o backup.tgz -d backup.tgz.gpg

Of course, this only works if I have already generated a public-private key pair and installed it with gpg. In my case, I have done so using Digital Ocean's guide at https://www.digitalocean.com/community/tutorials/how-to-use-gpg-to-encrypt-and-sign-messages-on-an-ubuntu-12-04-vps. The ABCD1234 in the encryption command refers to one of the public keys installed on my system. This guide also covers how to share your public key and install others' public keys to send and receive encrypted files.

A: GnuPG is what I've chosen to used for this process and because you've stated that decryption steps where to opaque (I agree in this usage instance) I've also worked on that side of the problem too. Check the projects' Travis-CI build logs for what features currently work as designed and the travis.yml file for following along with the logs' output. Basically you'll need three scripts from this project; the keygen script, decryption helper script, and named pipe listener script. The keygen script & decryption helper script should be used on the device that will preform decryption and the named pipe listener script should be on the device preforming encryption.
The encrypting named pipe listener script accepts strings, file paths, or directory paths once setup and outputs encrypted results in a predictable fashion.
Below are example commands that could be placed into your nightly backup script for encryption and for directories compression+encryption
echo "some messages text" > /path/to/named.pipe
## Message text is ASCII armor encrypted and appended to specified file when script was stated
echo "${HOME}/Documents" > /path/to/named.pipe
## Directories are compressed with tar and encrypted with output to time stamped file in bulk output directory
echo "${HOME}/.bash_history"  > /path/to/named.pipe

For decryption you'll want to check out how the build scripts .travis-ci/script_decrypt.sh & .travis-ci/test_search_script_decrypt.sh for how the appended strings of encrypted data are recovered and how bulk files/directories are restored.
Of course with stuff this experimental it's best to not use primary key pares (kinda why the keygen script was written) and it should not be used on important data until you're confident in how to restore it to readable form.

A: I used the great solution of Florian Diesch above, but ran into this issue:
gpg: problem with the agent: Inappropriate ioctl for device
gpg: error creating passphrase: Operation cancelled
gpg: symmetric encryption of '[stdin]' failed: Operation cancelled

In addition to work with my Ubuntu 20.04, I needed to set for gpg:
$GPG_TTY=$(tty)
$export GPG_TTY

like described here
Then I could proceed with the solution of Florian! Thanks!
A slightly different method which works also well with linux (Ubuntu 20.04) is described here


text:
Q: How do I average DateTime values in SQL Azure with Entity Framework? I have a SQL query that needs to average many datetime values server-side (in SQL Server). For example purposes, let's just consider it's a simple query like this on a table with millions of records:
SELECT
    SomeField,
    AVG(CAST(ADateTime AS decimal(18,8))) AS NumericRepresentation
FROM MyTable
GROUP BY SomeField

As shown, I can't simply take AVG(ADateTime) because SQL Server isn't happy with doing that, but converting it to a Decimal (and later converting it back to a DateTime) works well enough for me.
The obvious way to do something comparable with EntityFramework is to use .Select(tbl => tbl.ADateTime.Ticks).Average(), but this fails at runtime because DateTime.Ticks doesn't translate through Linq-to-Entities.
How should I best go about this? My main need is to average datetime values in some way. The temporary representation (decimals, ticks, etc) isn't terribly important as long as it can be translated back to a DateTime either in SQL or .NET code. What is important, though, is that the averaging is done in SQL Server (I have some fairly complex calculations with this over many records) and I can somehow have the translated DateTime in .NET (whether the translation happens in SQL Server or in .NET, I don't care).

A: In pure SQL you can do average on a date field with something like this:
-- the smallest date you could possibly have in your data
DECLARE @MinDate DATE = '1/1/1900'
SELECT
    SomeField,
    DATEADD(DAY, AVG(DATEDIFF(DAY, @MinDate, ADateTime)), @MinDate) as AvgDateTime
FROM MyTable
GROUP BY SomeField

Not sure yet how to translate this to LINQ :)
UPD: Here is the LINQ code:
private static void Test(IQueryable<SomeClass> data)
    {
        var minDate = DateTime.MinValue;
        var avgMilliseconds = data.Select(x => x.SomeDateField.Subtract(minDate).TotalMilliseconds).Average();
        var avgDate = minDate.AddMilliseconds(avgMilliseconds);
        Console.WriteLine(avgMilliseconds);
        Console.WriteLine(avgDate);
    }

A: EF LINQ expressions can make use of SqlFunctions class to make sure the conversion happens correctly.
DateTime minDate = new DateTime(1900,1,1);
var avg = MyTable.Select(myrow => SQLFunctions.DateDiff("second",myrow.ADateTime,minDate).Average();
DateTime avgDate = minDate.AddSeconds(avg);

Previous answer, should be disregarded:
Use Convert.ToDouble. EntityFramework should be able to translate this LINQ to SQL is able to CONVERT(float,...) as long as your column is actually a DateTime and not DateTime2 or DateTimeOffset, but unfortunately Entity Framework is not able to recognize this construct.
.Select(tbl => Convert.ToDouble(tbl.ADateTime)).Average()

An alternate choice is to do it client side:
.Select(tbl => tbl.ADateTime).ToArray().Select(dt => dt.Ticks).Average()

though clearly that's not preferred if you're averaging millions of rows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FindWindowEx is not running I have a problem with the API windows function FindWindowEx, in fact I obtain the handle of the MainWindow of the process, but when i try to retrieve the handle of one of its buttons with FindWindowEx, it's not running.
I had verified the window and its buttons with spy++, and everything runs well, even the handle of the mainwindow returned by my program matches the spy++'s one. i have tested the error code returned by "Marshal.GetLastWin32Error()",
 i always obtain error 1008. i have searched in many old posts dealing with my problem, but i hadn't find any solution for it. here is my code :
DllImport("user32.dll" , CharSet = CharSet.Auto)]
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
 // ....
 IntPtr hwnd = proc.MainWindowHandle;
        string str = proc.MainWindowTitle;
        Console.WriteLine("Main window Title : " + str);
        Console.WriteLine("Main window Handle : " + hwnd.ToString());
        //Get a handle for the "suivant" button
        IntPtr hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "suivant" );
        int error = Marshal.GetLastWin32Error() ;

A: as Mr Hans Passant say, the class name is unpredictable, so the solution is to not specify the class name in the FindWindowEx function so to obtain all the controls handles in the mainwindow we can use :
do {
           IntPtr hwndchild = FindWindowEx(hwndparent, hwndchild , null, null) ;
        }while( hwndchild != IntPtr.Zero );

and we can find the handle of the "suivant" button in the main window :
IntPtr hwndchild = FindWindowEx(hwnd, hwndchild , null, "suivant") ;

Thank you for your help.


text:
Q: Equivalence of two pictures of odd $K$-theory One can show that two functors $K^0$ and $K_0(C(-))$ from the category of compact topological spaces to the category of abelian groups are naturally equivalent. The first one is topological $K$-theory and the second is operator $K$-theory composed with the functor of "continuos functions". I wonder whether the same is true for $K^1$. Natural idea is to reduce this case to the even case using suspension functor, however there are two difficulties:
-first of all in the category of $C^*$-algebras suspension is defined by $SA=C_0(\mathbb{R}) \otimes A$ therefore it produces nonunital algebras and I don't know whether there is equivalence of functors $K^0$ and $K_0(C(-))$ in the locally compact case.
-secondly, this suspension as defined above is not the same as the ordinary topological suspension but it corresponds rather to crossing with $\mathbb{R}$.
So to summarize, my question is

Do we have natural equivalence of functors $K^1$ and $K_1(C(-))$ and do we have natural equivalence of $K^0$ and $K_0(C(-))$ in the locally compact case?

A: The answer is basically "yes, because the definitions are rigged to make it so".  The point is that you have to be careful both with C*-algebra K-theory in the non-unital case and with topological K-theory in the non-compact case, and the standard ways of being careful in both areas are compatible.
Recall that the reduced K-theory of a C*-algebra (unital or not) is by definition:
$$\tilde{K}(A) = \ker(K(A^+) \to K(\mathbb{C})$$
where $A^+$ is the unitalization of $A$ (just $A \oplus \mathbb{C}$ in the unital case) and the map $K(A^+) \to K(\mathbb{C})$ is induced by $A^+ \to A^+/A \cong \mathbb{C}$.  Note that if $A = C_0(X)$ where $X$ is locally compact then $C_0(X)^+ \cong C_0(X^+)$ where $X^+$ is the one point compactification of $X$, and the map $C_0(X^+) \to \mathbb{C}$ corresponds to evaluation at the point at infinity, i.e. it is induced by the inclusion of infinity in $X^+$.
Applying all of this to the suspension of a unital C*-algebra $A$, we get:
$$K_1(A) \cong \ker(K_0(C(S^1)) \otimes A \to K_0(\mathbb{C}))$$
where the map is induced by the inclusion of the point at infinity of $\mathbb{R}$ in $S^1$.
On the other hand the K-theory of the reduced suspension of a pointed compact space $(X, x_0)$ is isomorphic to the reduced K-theory of $S_1 \times X$, i.e.
$$K^1(X) \cong \ker(K^0(S^1 \times X) \to K^0(\{\infty, x_0\}))$$
So the two definitions of degree 1 (or perhaps it should really be degree -1) K-theory agree.


text:
Q: Personalizar Auth de Laravel Tengo una gran duda, hoy estuve curioseando el Auth de Laravel, el problema que no pude resolver fue lo siguiente:
Modifiqué la migración users por:
public function up()
    {
        Schema::create('sis_users', function (Blueprint $table) {
            $table->increments('id_user');
            $table->string('name_user');
            $table->string('email_user')->unique();
            $table->string('password_user');
            $table->rememberToken();
            $table->timestamps();
        });

Modifiqué los Modelos, pero aun no logro encontrar los demás archivos donde debo realizar más modificaciones.

A: Lo que tenés que hacer es modificar la migración, el Modelo, el controlador y la Vista del formulario de Login.
Justo ayer hice un gist en github para explicar esto. Como hacer login con username en lugar de por email en Laravel. Igualmente te pongo la explicación y el código acá. Espero sea lo que necesitás.
Saludos
El controlador App\Http\Controllers\Auth\LoginController implementa el trait AuthenticatesUsers y este es el encargado de realizar la validación del Login. El método validateLogin() valida el campo email por defecto pero este lo obtiene del método username() que retorna el campo email por eso si lo que queremos es validar el login por otro campo (En este ejemplo será el campo 'username') debemos:
1- En la migracion de la tabla users (2014_10_12_000000_create_users_table.php) agregar el campo username es importante que este sea de tipo unique
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

2- En el modelo App\User agregar el campo username a los fillables.
protected $fillable = [
    'username', 'name', 'email', 'password',
];

3- En el controlador App\Http\Controllers\Auth\LoginController agregar el método username()
public function username()
{
    return 'username';
}

4- En la vista blade auth/login.blade.php modificar el formulario de login. En lugar de un campo de tipo email colocamos como campo text y además tenemos que cambiar el name.

    {{ __('Username') }}

        <input id="email" type="text" class="form-control{{ $errors->has('username') ? ' is-invalid' : '' }}" name="username" value="{{ old('username') }}" required autofocus>

        @if ($errors->has('username'))

                {{ $errors->first('username') }}

        @endif

Y listo, podemos utilizar el auth por defecto de Laravel pero ahora nos logueamos utilizando el username en lugar del email


text:
Q: App Bar Icon XAML WP8 I wish to use this icon for my app bar button on a windows phone app.
I can do it using the .png files. But how to use it in XAML for Windows Phone.
I am looking for a way to do it like that in Windows 8. ie- using it with Content Tag and using a Font to draw it.

A: This is not possible with the current Windows Phone SDK.
The ApplicationBarIconButton only support rendered images.

A: Download and add the image to the project.
/Assets/1F698-Car.48.png

In Xaml:
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBarIconButton IconUri="/Assets/1F698-Car.48.png"
                                        Text="Car" />
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>


text:
Q: Swap suddenly vanished from Debian? Everything has been going fine for 6 months now until my swap suddenly vanished today. Now that I look into it, I find that my disk partitioning is a bit weird. What happened to it, and what should I do to recover it quickly without having to reinstall everything? (I need to finish a job before I do a fresh install again)
Here is my /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/ubuntu--vg-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda1 during installation
UUID=ede3c189-5d39-4f55-b263-0d6bcafc5d7b /boot           ext4    defaults        0       2
/dev/mapper/ubuntu--vg-swap_1 none            swap    sw              0       0
/dev/sr0        /media/cdrom0   udf,iso9660 user,noauto     0       0
# /dev/sdb1       /media/usb0     auto    rw,user,noauto  0       0
# /dev/sdc1       /media/usb1     auto    rw,user,noauto  0       0

(why is there "Ubuntu" there by the way?)
Here is the result of sudo fdisk -l /dev/sda:
Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000aabb9

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      499711      248832   83  Linux
/dev/sda2          501758   625141759   312320001    5  Extended
/dev/sda5          501760   625141759   312320000   8e  Linux LVM

As for lvm information, here is the output of ls -l /dev/mapper
total 0
crw------T 1 root root 10, 236 juin  29 07:28 control
lrwxrwxrwx 1 root root       7 juin  29 07:28 ubuntu--vg-root -> ../dm-0
lrwxrwxrwx 1 root root       7 juin  29 07:28 ubuntu--vg-swap_1 -> ../dm-1

.. the output of lvscan
ACTIVE            '/dev/ubuntu-vg/root' [294,10 GiB] inherit
ACTIVE            '/dev/ubuntu-vg/swap_1' [3,74 GiB] inherit

.. and the output of pvscan
PV /dev/sda5   VG ubuntu-vg   lvm2 [297,85 GiB / 12,00 MiB free]
Total: 1 [297,85 GiB] / in use: 1 [297,85 GiB] / in no VG: 0 [0   ]

.. and every day it looks more clear that we might have not wiped Ubuntu properly from my disk that night -_-
Is there a way I can quickly get my swap back before I get time to wipe all this?

A: To enable the swap device you can
swapon /dev/mapper/ubuntu--vg-swap_1

If there is an error with that swap space, because it was destroyed somehow, you can reformat the swap device with
mkswap /dev/mapper/ubuntu--vg-swap_1

Check the related manual pages swapon(1) and mkswap(1) for more information.


text:
Q: Андроид адаптер Мне нужно проверить посещаемость. У меня есть бд со списком фамилий и столбцом check (0 и 1). В итоге при запуске приложения считывается значение check в CheckBox, и при нажатии кнопки Сохранить все значения CheckBox записываются в бд.
Для этого мне нужно создать адаптер и объединить TextView и CheckBox, иначе при прокрутке значения CheckBox меняются.
Нашел примеры создания CustomAdapter extends SimpleCursorAdapter, но ничего не понял.
Кто может помочь мне с созданием адаптера?

item.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/ID"
        android:layout_width="wrap_content"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/NAME"
        android:layout_width="wrap_content"
        android:gravity="center_vertical"
        android:layout_height="50dp"
        android:layout_marginLeft="40dp"/>

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:layout_marginRight="20px"
        android:layout_alignParentRight="true"
        />

</RelativeLayout>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="40dp">
    </ListView>

    <LinearLayout
        android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">
    <Button

        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="назад"
        android:layout_weight="1"
        >
    </Button>

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Сохранить"
        android:layout_weight="1"
        >
    </Button>
</LinearLayout>

</RelativeLayout>

DatabaseHelper
class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_PATH;
    private static String DB_NAME = "bd.db";
    private static final int SCHEMA = 1;
    static final String TABLE = "bd";

    static final String COLUMN_ID = "_id";
    static final String COLUMN_NAME = "name";
    static final String COLUMN_CHECK = "check";
    private Context myContext;

    DatabaseHelper(Context context) {
        super(context, DB_NAME, null, SCHEMA);
        this.myContext=context;
        DB_PATH =context.getFilesDir().getPath() + DB_NAME;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,  int newVersion) {
    }

    void create_db(){
        InputStream myInput = null;
        OutputStream myOutput = null;
        try {
            File file = new File(DB_PATH);
            if (!file.exists()) {
                this.getReadableDatabase();

                myInput = myContext.getAssets().open(DB_NAME);

                String outFileName = DB_PATH;

                myOutput = new FileOutputStream(outFileName);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }

                myOutput.flush();
                myOutput.close();
                myInput.close();
            }
        }
        catch(IOException ex){
            Log.d("DatabaseHelper", ex.getMessage());
        }
    }
    public SQLiteDatabase open()throws SQLException {

        return SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    }

}

MainActivity
public class MainActivity extends AppCompatActivity {

    ListView userList;
    DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    Cursor userCursor;
    SimpleCursorAdapter userAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        displayListView();
    }

    private void displayListView() {

        databaseHelper = new DatabaseHelper(getApplicationContext());
        databaseHelper.create_db();
    }

    @Override
    public void onResume() {
        super.onResume();

        db = databaseHelper.open();

        userCursor = db.rawQuery("select * from " + DatabaseHelper.TABLE, null);

        String[] from = new String[]{DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_NAME};
        int[] to = new int[]{R.id.ID, R.id.NAME};

        userAdapter = new SimpleCursorAdapter(this, R.layout.item, userCursor, from, to, 0);
        userList = (ListView) findViewById(R.id.list);
        userList.setAdapter(userAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        db.close();
        userCursor.close();
    }
}


text:
Q: Copy Data from multiple text files into an existing sheet I am looking to allow the user to select upto 5 text files at a time and copy paste the data into an existing sheet within excel. Each text file is to be added after the previous file. Meaning if the first file has been imported from Column A1 to A200, then second file must be pasted from row A201 and so forth and so on. I am using the following code which allows the user to select one file only. i am looking to just copy paste the data from these text files into the excel without any formatting. Any help will be greatly appreciated.

Sub importdata()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
    FileToOpen = Application.GetOpenFilename(Title:="Select file extracted", FileFilter:="All Files (*.*),*.*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A:A").Copy
        ThisWorkbook.Worksheets("rawdata").Range("A1").PasteSpecial xlPasteValues
        OpenBook.Close False
     End If
End Sub

A: Give this a try:
Option Explicit ' It is a good practice to use this to force the compiler to ask for
                ' Var declaration before use it

Sub importdata()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Dim RngCopy As Range  ' Var to store the range you want to copy
    Dim RngPaste As Range ' Var to store the rante you want paste the txt file data
    Dim A As Worksheet    ' ActiveSheet of the open book stored in "OpenBook" var
    Dim B As Worksheet: Set B = ThisWorkbook.Worksheets("rawdata") '... Well RawData...
    Dim r
    Dim p
    Dim i
    FileToOpen = Application.GetOpenFilename( _
                        Title:="Select file extracted", _
                        FileFilter:="All Files (*.*),*.*", _
                        MultiSelect:=True)
    'As mention Ron Rosenfeld, you need to use Multiselect

    'Since you want several files, you need a LOOP, a For Loop!
    For Each i In FileToOpen ' no matter if is 1 or many files you take, will work
        If FileToOpen = "False" Then Exit Sub 'But if you take no files will exit with no error
    'If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen) 'the macro open the file
        Set A = OpenBook.ActiveSheet 'Store the active sheet inside A
        r = A.Range("A1").SpecialCells(xlCellTypeLastCell).Row 'Here look for the last cell, this is like
                                                               ' press the CTRL+END keys in the keyboard
                                                               'I asume your data in only en column A
                                                               'goto to the last cell and take the number of the row
        Set RngCopy = A.Range(Cells(1, 1), Cells(r, 1)) 'Take the whole range, and I asume you want to take
                                                        'From A1 to the last row, A1000 ej.
        'OpenBook.Sheets(1).Range("A:A").Copy
        B.Activate 'Go to rawdata!
        p = B.Range("A1000000").End(xlUp).Row + 1 'Here! From the very last cell.
                                                  'Notice: if you have Excel 97 and before, you need to change to
                                                  '65000, if not, 1000000 will work.
                                                  'From the A1000000 to the top, tell the row + 1
                                                  'Mean... one row bellow the last row in your data.

        Set RngPaste = B.Range(Cells(p, 1), Cells(p + r, 1)) 'Look Here!
                                                             'The last cell (last row + 1 = p) of your data in rawData plus
                                                             'The data you want to insert bellow that data.
                                                             'p + the count of the rows in the new data (r)
                                                             'p + r
                                                             'all this just in column A
        RngPaste.Value = RngCopy.Value
        'We don't use COPY, only if is necesary!
        'We transfer data from here to there!
        'Now we can tell B = A
        'B.Range("A1").PasteSpecial xlPasteValues
        OpenBook.Close False 'Good Boy!!!

        'it is good practice to clean your vars/objects
        Set OpenBook = Nothing
        Set A = Nothing
        Set B = Nothing
        Set RngCopy = Nothing
        Set RngPaste = Nothing
     'End If
    Next i
End Sub

Tell me if is right, to edit and fix anything.


text:
Q: EmberJS: Resolve promise in the success of processing request I adapted the ajax call in RESTAdapter for retrieving the data from vert.x bus bridge. But, I have a problem with retrieving the promise in the success part of processing request.
I suppose that the problem is with form of data structure that Ember expects.
This is the code of my adapter:
var VertxAdapter = DS.RESTAdapter.extend({
  protocol: 'http',
  host: 'localhost',
  port: '4200',
  addressMapping: {
    "GET localhost/mindMaps": "mindMaps.list"
  },
  pendingRequests: [],

  vertx: function() {
    var adapter = this;

    if (typeof adapter._vertx === 'undefined') {
      adapter._vertx = new vertx.EventBus(adapter.protocol + '://' + adapter.host + ':' + adapter.port + '/eventbus');
      console.log('initialize vertx');
      adapter._vertx.onopen = function() {
        // TODO: register for messages send from server to this client

        adapter.processPendingRequests.apply(adapter);
      };
    }

    return adapter._vertx;
  },

  ajax: function(url, type, params) {
   console.log(url, type, params);

    var adapter = this;

    var messageAddress = adapter.addressMapping[type + " " + url];

    return new Ember.RSVP.Promise(function(resolve, reject) {
      var success = function(json) {
        Ember.run(null, resolve, json);
      };
      var error = function(json) {
        Ember.run(null, reject, json);
      };

      if(adapter.vertx().readyState === vertx.EventBus.OPEN) {
        console.log('ready state');
        adapter.processRequest(messageAddress, params, success, error);

      } else {
        var pendingReq = {
          address: messageAddress,
          params: params,
          success: success,
          error: error
        };
        console.log('push pending req');
        adapter.pendingRequests.push(pendingReq);

      }

    });

  },

  processPendingRequests: function() {
    console.log('processPendingRequests');
    var adapter = this;
      adapter.pendingRequests.forEach(function(req){
        console.log(req);
          adapter.processRequest(req.address, req.params, req.success, req.error);
      });
  },

  processRequest: function(address, params, success, error) {
    console.log(address, params, success, error);
    var adapter = this;
    adapter.vertx().send(address, params, function(json){
      //TODO: implement
      //console.log(arguments);
      console.log(JSON.stringify(json));

     success(json);

      // error(json);

    });

    adapter.pendingRequests = [];
  }

});

export default VertxAdapter.extend({
    port: '8080'
});

And this is the server:
var eventBus = require("vertx/event_bus");
var mindMaps = {};

var extend = function(obj, props) {
   for (var prop in props) {
      if (props.hasOwnProperty(prop)) {
         obj[prop] = props[prop];
      }
   }

   return obj;
};

eventBus.registerHandler("mindMaps.list", function(args, responder) {
    responder(
    {
        "data": Object.keys(mindMaps).map(function(key) {
            return extend(
                {
                    "type": "mindMaps"
                },
                mindMaps[key]
            );
        })
    });
});

eventBus.registerHandler("mindMaps.save", function(mindMap, responder) {
    if (!mindMap.id) {
        mindMap.id = Math.floor((Math.random() * 100) + 1);
    }
    mindMaps[mindMap.id] = mindMap;
    responder({
        "data": mindMap
    });
});

eventBus.registerHandler("mindMaps.delete", function(args, responder) {
    delete mindMaps[args.id];
    responder({});
});

Here is the console output:
{"data":[{"type":"mindMaps","name":"One","id":59},{"type":"mindMaps","name":"Two","id":99},{"type":"mindMaps","name":"Three","id":55}]}

WARNING: Encountered "data" in payload, but no model was found for model name "datum" (resolved model name using mind-maps@serializer:-rest:.typeForRoot("data"))

Error while processing route: mind-maps Assertion Failed: The response from a findAll must be an Array, not undefined Error: Assertion Failed: The response from a findAll must be an Array, not undefined

I suppose that I don't return the data from the server in a form that Ember expects me to.
Ideas?
BR,
Milan

A: Unless you also want to create your own serializer, your JSON needs to be in a specific format. You can see the format documented here.
If you're not able to modify your server to return that JSON format, you'll need to write your own Serializer, and convert your data into the format listed here.
If this sounds a little bit much, that's because it is. I think Ember-Data's adapters and serializers is its number one issue. Unfortunately, there aren't many easy ways to do what you want.


text:
Q: sql server access ONLY the previous record based on a selection Given the following table
id  short_name  long_name   category    departure   rec_order
1548    AAA AAA AA  station 10:00   1
1548    BBB BBB BB  station 11:10   2
1548    CCC CCC CC  station 12:30   3
1548    DDD DDD DD  border  15:30   4

I want to access only last the row (station) before the border.
Basically return only
CCC CCC CC  station 12:30   3

Because the database is rather big and even this timetable is in the real life a complicated structure and we have in indexed view for putting together all the data (here is a simplification for the sake of example) I'm looking for a higher performance solution (possibly no cross join).
I've tried the selection with lag and/or lead, as well as offset fetch but those solutions were not working as soon as I put in the where clause where category = 'border' as it only selects the border row.
This query is working, but I'm looking for a more optimised solution:
select top 1 M1.short_name  M1.long_name
from V_TIMETABLE M1 WITH ( NOEXPAND )
join
(
select top 1 rec_order, id
from V_TIMETABLE V WITH ( NOEXPAND )
where   V.id = 1548
and category = 'border'
order by rec_order desc
) M2 on M1.id = M2.id
where M1.rec_order < M2.rec_order
order by M1.rec_order desc

A: This works for given data
    ;with cte
    as
    (
    select
    id, short_name , long_name,   category ,   departure  , rec_order,
    row_number() over (partition by id order by departure desc) as rownum
   from table where category<>'border'
    )
    select * from cte where rownum=1

A: I just want to point out an alternative solution:
select t.*
from (select t.*,
             lead(category) over (partition by id order by departure) as next_category
      from t
     ) t
where next_category = 'border';

Important note:  This will not return ids that have no border in them.  It will also return multiple rows for ids that have border multiple times.  These seem more in line with the question actually asked than always selecting one row -- and is consistent with the sample code provided in the question.


text:
Q: How do servlets work? Instantiation, sessions, shared variables and multithreading Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.
Now, if 2 or more users send request to this server then what happens to the session variables?
Will they all be common for all the users or they will be different for each user?
If they are different, then how was the server able to differentiate between different users?
One more similar question, if there are n users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately?
In other words, what happens to the instance variables?

A: Sessions

In short: the web server issues a unique identifier to each visitor on his first visit. The visitor must bring back that ID for him to be recognised next time around. This identifier also allows the server to properly segregate objects owned by one session against that of another.
Servlet Instantiation
If load-on-startup is false:

If load-on-startup is true:

Once he's on the service mode and on the groove, the same servlet will work on the requests from all other clients.

Why isn't it a good idea to have one instance per client? Think about this: Will you hire one pizza guy for every order that came? Do that and you'd be out of business in no time.
It comes with a small risk though. Remember: this single guy holds all the order information in his pocket: so if you're not cautious about thread safety on servlets, he may end up giving the wrong order to a certain client.

A: Session in Java servlets is the same as session in other languages such as PHP.  It is unique to the user.  The server can keep track of it in different ways such as cookies, url rewriting etc.  This Java doc article explains it in the context of Java servlets and indicates that exactly how session is maintained is an implementation detail left to the designers of the server.  The specification only stipulates that it must be maintained as unique to a user across multiple connections to the server.  Check out this article from Oracle for more information about both of your questions.
Edit There is an excellent tutorial here on how to work with session inside of servlets. And here is a chapter from Sun about Java Servlets, what they are and how to use them.  Between those two articles, you should be able to answer all of your questions.

A: When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).
During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information
Servlet engine creates servletConfig interface object encapsulating the above missing information into it
servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.
Q) In the lifetime of servlet how many times instantiation and initialization happens ??
A)only once (for every client request a new thread is created)
only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).
Q)How session concept works?
A)whenever getSession() is called on HttpServletRequest object
Step 1: request object is evaluated for incoming session ID.
Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).
Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.
Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.
Note:
1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine
2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code
Inshort form:
A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting)
when the servlet is instantiated, the init() method of the servlet is called
then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet
when the application is undeployed (the servlet container stops), the destroy() method is called.

A: Sessions - what Chris Thompson said.
Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup> element in web.xml). The same instance is used to serve subsequent requests.

A: ServletContext
When the servlet container (like Apache Tomcat) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server's memory. The web app's web.xml and all of included web-fragment.xml files is parsed, and each <servlet>, <filter> and <listener> found (or each class annotated with @WebServlet, @WebFilter and @WebListener respectively) will be instantiated once and be kept in the server's memory as well, registred via the ServletContext. For each instantiated filter, its init() method is invoked with a new FilterConfig argument which in turn contains the involved ServletContext.
When a Servlet has a <servlet><load-on-startup> or @WebServlet(loadOnStartup) value greater than 0, then its init() method is also invoked during startup with a new ServletConfig argument which in turn contains the involved ServletContext. Those servlets are initialized in the same order specified by that value (1 is 1st, 2 is 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the same order as they appear in the web.xml, web-fragment.xml, or @WebServlet classloading. In the event the "load-on-startup" value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.
When the servlet container is finished with all of the above described initialization steps, then the ServletContextListener#contextInitialized() will be invoked with a ServletContextEvent argument which in turn contains the involved ServletContext. This will allow the developer the opportunity to programmatically register yet another Servlet, Filter or Listener.
When the servlet container shuts down, it unloads all web applications, invokes the destroy() method of all its initialized servlets and filters, and all Servlet, Filter and Listener instances registered via the ServletContext are trashed. Finally the ServletContextListener#contextDestroyed() will be invoked and the ServletContext itself will be trashed.
HttpServletRequest and HttpServletResponse
The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (e.g. user with a web browser, or programmatically using URLConnection) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter in the chain and, eventually, the Servlet instance.
In the case of filters, the doFilter() method is invoked. When the servlet container's code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.
In the case of servlets, the service() method is invoked. By default, this method determines which one of the doXxx() methods to invoke based off of  request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.
The request object provides access to all of the information about the HTTP request, such as its URL, headers, query string and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made available for reuse.
HttpSession
When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and stores it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.
As per the HTTP cookie specification (a contract any decent web browser and web server must adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.
The HttpSession stays alive until it has been idle (i.e. not used in a request) for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.
On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HttpSession to be created, with an entirely new session cookie being used.
In a nutshell

*

*The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.

*The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among all requests in the same session.

*The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is not shared elsewhere.

*All Servlet, Filter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.

*Any attribute that is defined in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an attribute of its closest matching scope.

Thread Safety
That said, your major concern is possibly thread safety. You should now know that servlets and filters are shared among all requests. That's the nice thing about Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, init() and destroy() them for every single request.
You should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's not thread-safe! The below example illustrates this:
public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    }
}

See also:

*

*What is the difference between JSF, Servlet and JSP?

*Best option for Session management in Java

*Difference between / and /* in servlet mapping url pattern

*doGet and doPost in Servlets

*Servlet seems to handle multiple concurrent browser requests synchronously

*Why Servlets are not thread Safe?

A: The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods (2.3.3.1 Multithreading Issues, Page 9):

A servlet container may send concurrent requests through the service
  method of the servlet. To handle the requests, the Servlet Developer
  must make adequate provisions for concurrent processing with multiple
  threads in the service method.
Although it is not recommended, an alternative for the Developer is to
  implement the SingleThreadModel interface which requires the container
  to guarantee that there is only one request thread at a time in the
  service method. A servlet container may satisfy this requirement by
  serializing requests on a servlet, or by maintaining a pool of servlet
  instances. If the servlet is part of a Web application that has been
  marked as distributable, the container may maintain a pool of servlet
  instances in each JVM that the application is distributed across.
For servlets not implementing the SingleThreadModel interface, if the
  service method (or methods such as doGet or doPost which are
  dispatched to the service method of the HttpServlet abstract class)
  has been defined with the synchronized keyword, the servlet container
  cannot use the instance pool approach, but must serialize requests
  through it. It is strongly recommended that Developers not synchronize
  the service method (or methods dispatched to it) in these
  circumstances because of detrimental effects on performance

A: No. Servlets are not Thread safe
This is allows accessing more than one threads at a time
if u want to make it Servlet as Thread safe ., U can go for
Implement SingleThreadInterface(i)
which is a blank Interface there is no
methods
or we can go for synchronize methods
we can make whole service method as synchronized by using synchronized
keyword in front of method
Example::
public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException

or we can the put block of the code in the Synchronized block
Example::
Synchronized(Object)

{

----Instructions-----

}

I feel that Synchronized block is better than making the whole method
Synchronized

A: As is clear from above explanations, by implementing the SingleThreadModel, a servlet can be assured thread-safety by the servlet container. The container implementation can do this in 2 ways:
1) Serializing requests (queuing) to a single instance - this is similar to a servlet NOT implementing SingleThreadModel BUT synchronizing the service/ doXXX methods; OR
2) Creating a pool of instances - which's a better option and a trade-off between the boot-up/initialization effort/time of the servlet as against the restrictive parameters (memory/ CPU time) of the environment hosting the servlet.


text:
Q: Need a python script to search specific keywords in a collection of sql files returning the index of where each keyword was found I'm extremely new to python and I was just wondering how could I take a collection of files (sql), and using some specific keywords, find which line of code they are matched throughout all the files. Any notions, ideas or suggestions would be life savingly helpful.
Kind Regards
Tiago M

A: Solution
s = 'somestring'
names = ['file1.sql', 'file2.sql']
for n in names:
    f = open(n)
    lines = f.readlines()
    for i, l in enumerate(lines):
        if s in l:
            print 'line %d' % (i)

A: You want to look at the os.walk function then open each file and use in, string.find, or re.search on the lines of each file.  For example:
search_term = "where x > 1"
for directory, subdirectories, paths in os.walk("/path/to/sql_directory"):
    for path in paths:
        f = open(path, "r")
        for line_no, line in enumerate(f):
             if search_term in line: # could use re module functions here
                 print "%s(%d): %s"%(path, line_no, line)


text:
Q: How to automatically include/load css and js from modules in CodeIgniter using HMVC I have some modules in modules folder that have css and js folder and I am thinking of the way how to approach the automatic load of all this css and js files to my header of the template.
I was thinking of creating 2 modules called cssloader and jsloader that will be included in the header section of the template.
They would contain some php script that will put the urls of css (and js) in an array and this array will be outputed in the template like e.g.:
<?php echo Modules::run( 'cssloader/cssloader/_css_include_for_frontend' ); ?>

The urls will be grabed by some script that will be searching modules folder of the CI application and looking for css folder within and a file load_css.php with some defined constants or variables like
$css_loader_frontend['slider'] = array('slider.css',
                                       'slider_ie6.css'
                                      );
$css_loader_backend['slider']  = array('slider_admin.css');

This file will contain files that will be loaded e.g. slider.css (within slider module css folder)
And the similar scenario for javascript stuff.
Is my approach right or not and you would do it somehow different?
What do you think about it?
What would you do different and more effective?
Thanks

A: I Think this template class can help you, though, I was wondering why are you accessing assets files inside modules, I'm not well versed but as far as I know you should access files such as img, js, css and so on just on the level of system and application folders in a folder that could be named "public" or "assets" to avoid "Directory access is forbidden."


text:
Q: 401 Error When Uploading File to SharePoint Online with SaveBinaryDirect (C#) I am developing a tool that is supposed to upload files from a local drive to SharePoint online.
When I try to upload the file via SharePoint.Client.File.SaveBinaryDirect() I get a 401: Not authorized error
Here is my code:
var uploadFilePath = @"C:\TestFiles\testFile.pdf";
var uploadFileRelativePath = "/sites/my-site/MyLibrary/testFile.pdf";

using (var ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(site,
                    ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ClientSecret"]))
{
    using (var fileStream = new FileStream(uploadFilePath, FileMode.Open))
    {
        File.SaveBinaryDirect(ctx, uploadFileRelativePath, fileStream, true);
    }
}

The thing is, it works fine if I exchange the SaveBinaryDirect with the following code:
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(uploadFilePath);
newFile.Url = "testFile.pdf";
List docs = ctx.Web.Lists.GetByTitle("MyLibrary");
docs.RootFolder.Files.Add(newFile);
ctx.ExecuteQuery();

So my tool is clearly authorized to upload files. It just doesn't work with SaveBinaryDirect.
I would still like to upload the file with SharePoint.Client.File.SaveBinaryDirect. It's way less code and I don't have to manually get the list and folders.
Do you have any idea why I might get that 401 error?

A: You cannot use app only token with SaveBinaryDirect method: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/upload-large-files-sample-app-for-sharepoint
:

Only use this method if you're using a user-only authentication policy. A user-only authentication policy isn't available in a SharePoint Add-in, but can be used in native device add-ins, Windows PowerShell, and Windows console applications.


text:
Q: Mysql select query count until reach the condition with condition I have lists of users with his points and game id. I need to find the rank of the specified user based on the game order by the max(lb_point).
I have already done the query for getting the rank based on individual game as follows.
select count(*) AS user_rank
                                        from (
                                              select distinct user_id
                                              from leader_board
                                              where   lb_point >= (select  max( lb_point )
                                                     from leader_board
                                                     where user_id = 1
                                                     and game_id = 2 )
                                              and game_id = 2
                                        ) t

But i need to find the rank based on the overall game. Example i have 3 different games (1,2,3). By passing the user_id, i need to find his overall rank among all three games. Can you please help me on this?

lb_id    user_id   game_id   lb_point
------------------------------------------------
1         1        2         670
2         1        1         200
3         1        2         650
4         1        1         400
5         3        2         700
6         4        2         450
7         2        1         550
8         2        1         100
9         1        1         200
10        2        1         100
11        1        1         200
12        2        1         100
13        1        1         200
14        2        1         100
15        1        1         200
16        2        1         100
17        1        1         200
18        2        1         100
19        1        1         200
20        2        1         100
21        1        1         200
22        2        1         800

A: use sandbox;
/*create table t (lb_id int,   user_id int,  game_id int,   lb_point int);
truncate table t;
insert into t values
(1 ,        1,        2,         670),
(2 ,        1,        1,         200),
(3 ,        1,        2,         650),
(4 ,        1,        1,         400),
(5 ,        3,        2,         700),
(6 ,        4,        2,         450),
(7 ,        2,        1,         550),
(8 ,        2,        1,         100),
(9 ,        1,        1,         200),
(10,        2,        1,         100),
(11,        1,        1,         200),
(12,        2,        1,         100),
(13,        1,        1,         200),
(14,        2,        1,         100),
(15,        1,        1,         200),
(16,        2,        1,         100),
(17,        1,        1,         200),
(18,        2,        1,         100),
(19,        1,        1,         200),
(20,        2,        1,         100),
(21,        1,        1,         200),
(22,        2,        1,         800);

*/

select t.*
from
(
select s.*,@rn:=@rn+1 as rank
from
(
select  user_id, sum(lb_point)  points
from        t
where       lb_id = (select t1.lb_id from t t1 where t1.user_id = t.user_id and t1.game_id = t.game_id order by t1.lb_point desc limit 1)
group   by user_id
order       by points desc
) s
,(select @rn:=0) rn
) t
where   t.user_id = 1

The innermost query grabs the highest score per game per user and sums it.
The next query assigns a rank based on the aggregated score per user.
The outermost query selects the user.


text:
Q: SQL Server + Entity Framework basics I have this task to create a program in C# for managing company's staff. Only a brief overview - all the information about each employee is to be stored in MS SQL database. As a presentation layer, I have to use WPF and as a communication with database - LINQ to Entities.
The thing is - I managed to learn WPF on my own, but SQL is a serious matter. I've done some research, but even after reading many different tutorials I haven't found anything satisfying. I don't even understand the mechanics of this model. It is my understanding, that creating a database in SQL Server simply does nothing, because after one creates Entity model from the database, it is no longer tied to SQL Server. So updating data in created SQL database is no longer of use to the program itself. I may be wrong, and that is highly probable, but I just don't get it.
So, can anyone point me to a right direction?  What do I even have to know to start? Maybe some tutorials for such a noob?

A: ADO.NET Entity Framework (EF) was first released with Visual Studio 2008 and .NET Framework 3.5 Service Pack 1. So far, many people view EF as just another ORM product from Microsoft, though by design it is supposed to be much more powerful than just an ORM tool.A new data-access provider, EntityClient, is created for this new framework but under the hood, the ADO.NET data providers are still being used to communicate with the databases
The application no longer connects directly to a database or sees any database-specific construct; the entire application operates in terms of the higher-level EDM model.
This means that you can no longer use the native database query language; not only will the database not understand the EDM model, but also current database query languages do not have the constructs required to deal with the elements introduced by the EDM such as inheritance, relationships, complex-types, etc.
. LINQ to Entities allows developers to create flexible, strongly typed queries against the Entity Data Model (EDM) by using LINQ expressions and the LINQ standard query operators
Tutorial can be Found Here

A: It's basically the opposite of what you said actually:

It is my understanding, that creating a database in SQL Server simply
  does nothing, because after one creates Entity model from the
  database, it is no longer tied to SQL Server. So updating data in
  created SQL database is no longer of use to the program itself.

What happens is the Entity Framework (EF) connects to your database and gets the data from your SQL Server. From then, when you make changes in your app, EF operates in 'detached' sort of mode. This is probably the source of your confusion. The piece you are missing, is that you tell EF using ef.SaveChanges() to push all of the changes made in 'detached' mode, back to your database. So you make your changes in memory, then when you are ready, you tell EF to push those changes to the database.
Now to your other point, if you make a change directly to SQL Server (which I could see scenarios where this would occur), you certainly would run into issues with your 'detached' mode EF objects. I'm honestly not sure what would happen here, someone more experienced than me should say, that's a really interesting question that I'd also like to know the answer to.
Here are some tutorial infos that I found that seemed good:
http://www.microsoft.com/downloads/details.aspx?FamilyID=355c80e9-fde0-4812-98b5-8a03f5874e96&displaylang=en
which is actually in this answer
and also:
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
EDIT: when I talk about detached mode, understand that inside EF there are various modes that you can operate in, one of which is detached mode. I hated to use the term 'detatched mode' in my answer b/c I know others will come along and say that term is confusing, and they are correct. Just understand that inside EF there is a 'detatched' mode and it is somewhat of an advanced topic.

A: Entity Framework is very easy and very powerful ORM. My suggestion to you would be to start with http://www.asp.net/entity-framework. Here you can find a lot of Get Started tutorials to help you up and running in a short time. Although these tutorials are tied with ASP.NET, you can very easily understand them and use them with other platforms.


text:
Q: Accessibility when including SVGs directly I have been using boilerplate .ir for sometime to replace text with images for logos and icons.
.ir {
  background-color: transparent;
  border: 0;
  overflow: hidden;
  white-space: nowrap;
  *text-indent: 100%;
}

.ir:before {
  content: "";
  display: block;
  width: 0;
  height: 150%;
}

But now I would like to start using svgs for all my icons and logos and when using svgs as backgrounds or as <img> you can't control the innards of the svg ie i wouldn't be able to change a fill color.
So what I want to know is, what is the best way to include the svg while maintaining good SEO for titles and links?
Or is there any way of replacing text with an svg?
Or adding textual description like an alt tag or anything like that?
edit
I stated this was for SEO, but with hindsight, i'm thinking in terms of accessibility.
When including an svg image how would I describe what it is to a screen reader, in a similar way to the <img src="#" alt="image description"> or the .ir method above?

A: You can add a <desc> tag as the first element inside your SVG. Give it a unique id attribute and then add an aria-labelledby attribute to the SVG element itself with the value of this attribute the ID of the desc element.
This will work in all browsers and screen readers that I know-of.
If you have other elements inside your SVG (e.g. text elements), you will want to set all of them to aria-hidden="true" so that those screen readers that do read that text do not redundantly read additional information from the SVG itself.
Here is an example
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="none" x="0px" y="0px" width="100px" height="50px" viewBox="0 0 100 50" aria-labelledby="a11yTitle" tabindex="0">
    <desc id="a11yTitle">This is an image with some example SVG text in it</desc>
    <text aria-hidden="true" writing-mode="lr"><tspan x="11.35" y="10.85" baseline-shift="0%" kerning="0" font-family="Arial_Bold_Bold" font-weight="bold" font-size="12" fill="#990099" xml:space="preserve">Cool SVG text</tspan></text>
</svg>


text:
Q: Uniqueness and existence of solutions of linear systems with indefinite matrices Let $K, M\in \mathbb{C}^{n\times n}$ be positive definite matrices and consider the following linear system:
$$(M-K)\vec{u}=\vec{b}\quad (1)$$
There are three cases of existence and uniqueness of solutions of this system:
Case (1): $M-K$ is positive or negative definite: $M-K$ is then nonsingular a unique solution exists.
Case (2): $M-K$ is positive or negative semidefinite:
$M-K$ is then singular and

*

*infinitely many solutions exist;

*no solutions exist (inconsistent system)

Case (3): $M-K$ is indefinite:

*

*$M-K$ is nonsingular and a unique solution exists;

*$M-K$ is singular and infinitely many solutions exist;

*$M-K$ is singular no solutions exist (inconsistent system)

So, all in all, system (1) can possibly take any of the possibilities of existence and uniqueness of solutions.
I'd appreciate if you could comment on this: is this all true? Thanks.


text:
Q: Multipe doughnut charts on one page with text in center using Chart.js I am displaying one doughnut chart on a web page with chart.js with some text in the center of the doughnut. The problems is when adding multiple dounghnut charts on the same page. The center text is overlapped on all charts.
Result looks like this doughnut chart with overlapping text
Here is a fiddle : https://jsfiddle.net/jaklar/ng1y18yo/1/
HTML code:
`

            <canvas id="myChart1" width="150" height="150"></canvas>
            <canvas id="myChart2" width="150" height="150"></canvas>

`
javascript
'
var data = {
  labels: [
    "Red",
    "Blue"
  ],
  datasets: [
    {
      data: [100, 100],
      backgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB"
      ]
    }]
};

var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
  type: 'doughnut',
  data: data,
  options: {
    responsive: true,
    cutoutPercentage: 75,
    legend: {
      display: false
    }
  }
});

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx;

    ctx.restore();
    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";

    var text = "100%",
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});

var data = {
  labels: [
    "Red",
    "Blue"
  ],
  datasets: [
    {
      data: [300, 0],
      backgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB"
      ]
    }]
};

var promisedDeliveryChart = new Chart(document.getElementById('myChart2'), {
  type: 'doughnut',
  data: data,
  options: {
    responsive: true,
    cutoutPercentage: 75,
    legend: {
      display: false
    }
  }
});

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx;

    ctx.restore();
    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";

    var text = "9%",
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});

'

A: There is no need to register separate plugin for different charts. This could be achieved by registering just a single plugin for both the charts.
also, your chart plugin has some flaws to it. here is the corrected version of the plugin ...
Chart.pluginService.register({
    beforeDraw: function (chart) {
        var width = chart.chart.width,
            height = chart.chart.height,
            ctx = chart.chart.ctx;
        ctx.restore();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        var text = chart.config.options.elements.center.text,
            textX = Math.round((width - ctx.measureText(text).width) / 2),
            textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.save();
    }
});

you would also need to set the following option for both the charts ...
elements: {
    center: {
        text: '50%' //set as you wish
    }
}

ᴅᴇᴍᴏ

Chart.pluginService.register({
    beforeDraw: function (chart) {
        var width = chart.chart.width,
            height = chart.chart.height,
            ctx = chart.chart.ctx;
        ctx.restore();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        var text = chart.config.options.elements.center.text,
            textX = Math.round((width - ctx.measureText(text).width) / 2),
            textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.save();
    }
});

// chart1
var data = {
    labels: ["Red", "Blue"],
    datasets: [{
        data: [50, 50],
        backgroundColor: ["#FF6384", "#36A2EB"],
        hoverBackgroundColor: ["#FF6384", "#36A2EB"]
    }]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
    type: 'doughnut',
    data: data,
    options: {
        elements: {
            center: {
                text: '50%'  //set as you wish
            }
        },
        cutoutPercentage: 75,
        legend: {
            display: false
        }
    }
});

// chart2
var data = {
    labels: ["Red", "Blue"],
    datasets: [{
        data: [75, 25],
        backgroundColor: ["#FF6384", "#36A2EB"],
        hoverBackgroundColor: ["#FF6384", "#36A2EB"]
    }]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart2'), {
    type: 'doughnut',
    data: data,
    options: {
        elements: {
            center: {
                text: '75%'  //set as you wish
            }
        },
        cutoutPercentage: 75,
        legend: {
            display: false
        }
    }
});

        <canvas id="myChart1" width="150" height="150"></canvas>
        <canvas id="myChart2" width="150" height="150"></canvas>

A: Line : 98 replace with below: Actually the text is proper but X and Y cordinate are same so it is overlapping. I have increase Y axis here so it comes down(if you want to keep upper side do decrease value of Y axis) and X make same so both start from same position.
ctx.fillText(text, textX, textY + 25);


text:
Q: Calculating arithmetic mean (one type of average) in Python Is there a built-in or standard library method in Python to calculate the arithmetic mean (one type of average) of a list of numbers?

A: Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));

A: Instead of casting to float you can do following
def mean(nums):
    return sum(nums, 0.0) / len(nums)

or using lambda
mean = lambda nums: sum(nums, 0.0) / len(nums)

UPDATES: 2019-12-15
Python 3.8 added function fmean to statistics module. Which is faster and always returns float.

Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a
  float. The data may be a sequence or iterable. If the input dataset is
  empty, raises a StatisticsError.
fmean([3.5, 4.0, 5.25])
4.25
New in version 3.8.

A: You don't even need numpy or scipy...
>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3

A: from statistics import mean
avarage=mean(your_list)

for example
from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

and result is
3.0

A: I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0

In numpy, there's numpy.mean().

A: If you're using python >= 3.8, you can use the fmean function introduced in the statistics module which is part of the standard library:
>>> from statistics import fmean
>>> fmean([0, 1, 2, 3])
1.5

It's faster than the statistics.mean function, but it converts its data points to float beforehand, so it can be less accurate in some specific cases.
You can see its implementation here

A: NumPy has a numpy.mean which is an arithmetic mean. Usage is as simple as this:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335

A: Use statistics.mean:
import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.

A: def list_mean(nums):
    sumof = 0
    num_of = len(nums)
    mean = 0
    for i in nums:
        sumof += i
    mean = sumof / num_of
    return float(mean)

A: def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

Examples:
l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0

A: The proper answer to your question is to use statistics.mean. But for fun, here is a version of mean that does not use the len() function, so it (like statistics.mean) can be used on generators, which do not support len():
from functools import reduce
from operator import truediv
def ave(seq):
    return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]),
                           enumerate(seq, start=1),
                           (0, 0)))

A: I always supposed avg is omitted from the builtins/stdlib because it is as simple as
sum(L)/len(L) # L is some list

and any caveats would be addressed in caller code for local usage already.
Notable caveats:

*

*non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L) or from __future__ import division

*division by zero: the list may be empty. to resolve:
if not L:
    raise WhateverYouWantError("foo")
avg = float(sum(L))/len(L)

A: Others already posted very good answers, but some people might still be looking for a classic way to find Mean(avg), so here I post this (code tested in Python 3.6):
def meanmanual(listt):

mean = 0
lsum = 0
lenoflist = len(listt)

for i in listt:
    lsum += i

mean = lsum / lenoflist
return float(mean)

a = [1, 2, 3, 4, 5, 6]
meanmanual(a)

Answer: 3.5


text:
Q: Sending email with zip file in Python Script is working, i received zip file. But when i am trying to open zip file (WinRaR and 7-zip) i get error - archive is either in unknown format or damaged. Maybe problem related with encoding ???
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib

def send_mail():
    sender = '*****@mail.ru'
    password = '*************'

    smtp_obj = smtplib.SMTP('smtp.mail.ru', 587)
    smtp_obj.starttls()

    msg = MIMEMultipart()
    msg['Subject'] = 'Data from Experiment'
    msg['From'] = sender
    msg['To'] = sender

    with open(r'C:\Users\Admin\Desktop\Python\Python + SQL\Send_email\arch\arch.zip',encoding='CP866') as file:
    # Attach the file with filename to the email
        msg.attach(MIMEApplication(file.read(), Name='arch.zip'))

    # Login to the server
    smtp_obj.login(sender, password)

    # Convert the message to a string and send it
    smtp_obj.sendmail(sender, sender, msg.as_string())
    #smtp_obj.quit()

send_mail()

A: Do not pass an encoding when opening a zip file. That's binary data and should be treated as such! open(..., 'b')


text:
Q: C++ Have array values in an enum? I was wondering if it is possible to have an array value in an enum? Example
    enum RGB {
      RED[3],
      BLUE[3]

    } color;

That way RED could contain values of (255,0,0) since that is the RGB color code for red.

A: No you can't do that with an enum. It looks a lot like you want a class/struct:
class Color {
public:
    int red;
    int green;
    int blue;

    Color(int r, int g, int b) : red(r), green(g), blue(b) { }
};

Once you have that class defined, you can then put it into a container (e.g. array, vector) and look them up. You could use an enum to refer to elements in an array, for example.
enum PresetColor {
    PRESET_COLOR_RED,
    PRESET_COLOR_GREEN,
    PRESET_COLOR_BLUE,
};

...
Color presetColors[] = { Color(255, 0, 0), Color(0, 255, 0), Color(0, 0, 255) };

Color favouriteColor = presetColors[PRESET_COLOR_GREEN];

With that in mind, you could wrap all this up to be more maintainable, but I would say that's out of the scope of this question.

A: You cannot do that. The tokens in an enum can only hold integral values.
A possible solution:
struct Color {uint8_t r; uint8_t g; uint8_t b;};

Color const RED = {255, 0, 0};
Color const GREEN = {0, 255, 0};
Color const BLUE = {0, 0, 255};

A: To make a long story short: NO, it is not possible.

A: No, the definition of enums only allows for them to hold integer values.


text:
Q: How to include graphics in minimal code? [UPDATE]
I'm sorry, if my question is less clear. I mean is how to simplify the writing of syntax in main.tex to display images with the same settings,
    \begin{figure}[ht]
    \centering
    \includegraphics{Pictures/pic1.png}
    \caption{Picture 1}
    \label{fig:pic1}
    \end{figure}

with just write, maybe,
    \includegraphics[caption,label]{pic1.png}

[ORIGINAL QUESTION]
I am writing an ebook that contains some of graphics. Some of them generated by code (using TikZ), for example pic1.tex. I think it will be easier to edit if they save in a separated file. I drop all graphics in a folder named Pictures. I named all graphics with the same prefix pic, for example pic2.png, pic3.jpg, etc.
How to include them with a minimal code, say:
    \include{pic1.tex}

Than
    \begin{figure}[h]
    \centering
    \includegraphics{Pictures/pic1.tex}
    \caption{Picture 1}
    \label{fig:pic1}
    \end{figure}

A: If you want to be a best practitioner, consider the following.
Let your files and folders hierarchy be as follows.

*

*main.tex in Project.

*rules.jpg is in SubDir.

*behaviors.jpg is in ParentSiblingDir.

% main.tex
\documentclass{article}
\usepackage{graphicx}
\graphicspath{{SubDir/}{../ParentSiblingDir/}}

\newcommand\Insert[5][hbtp]{%
    \begin{figure}[#1]
        \centering
        \includegraphics[#2]{#3}
        \caption{#4}
        \label{#5}
    \end{figure}}

\begin{document}
\Insert{scale=.2}{behaviors}{Students' behaviors}{fig:behaviors}
\Insert{scale=.2}{rules}{Father's rules}{fig:rules}
\end{document}

Remarks:

*

*Use \graphicspath to register folders (directories) from which the images will be included or imported. The format is \graphicspath{{<relative path1>}{<relative path2>}{<relative path...>}}. Each path must be followed by /.

*The remaining code should be clear enough!


text:
Q: Load img source path from .NET program in HTML string my problem is simple, i am developing a service in asp .NET that loads locally an HTML string (already in a folder of the project) , writes some values on it and then converts it to a pdf using a library.
My problem is that the html contains an image that i am currently loading as a base64, i want to load the image path (contained in a folder inside the project) in the "src" attribute of the img component so that when i create the pdf it shows the proper image, but cannot get the syntax right, any ideas ?


text:
Q: Pandas/Python multiply columns by row Apologies if this is a simple question.
I have two dataframes each with the same columns. I need to multiply each row in the second dataframe by the only row in the first.
Eventually there will be more columns of different ages so I do not want to just multiply by a scalar.
I have used df.multiply()  and continue to get NaN for all values presumably because the two df are not matched in length.
Is there a way to multiply each row in one dataframe by a singular row in another?
age   51200000.0  70000000.0
SFH
0        0.75        0.25

.
age             51200000.0    70000000.0
Lambda
91.0       0.000000e+00  0.000000e+00
94.0       0.000000e+00  0.000000e+00
96.0       0.000000e+00  0.000000e+00
98.0       0.000000e+00  0.000000e+00
100.0      0.000000e+00  0.000000e+00
102.0      0.000000e+00  0.000000e+00
...        ...           ...
1600000.0  1.127428e+22  8.677663e+21

A: You can use mul by first row of df1 selected by iloc:
print (df2.mul(df1.iloc[0]))

Sample:
print (df1)
      51200000.0  70000000.0
age
0          0.75        0.25

print (df2)
      51200000.0  70000000.0
age
91.0         1.0         2.0
94.0         5.0        10.0
96.0         0.0         0.0

print (df2.mul(df1.iloc[0]))
      51200000.0  70000000.0
age
91.0        0.75         0.5
94.0        3.75         2.5
96.0        0.00         0.0


text:
Q: wp7-how to make a thread navigate pages I want to check for changes in the aplication state every time interval, and if it has changed, to open a window, and  give the user 10 seconds to press on the window, if he does press on the window, then to allow him to navigate freely in the window, and if he doesn't press, to return back to the window before. I thought to implement it with a thread running in the background and waking up every time interval I want. Maybe there is a better way?

A: This strikes me as a scenario with lots of potential issues.
How do you stop the "window" appearing at an inconvenient time to the user? (e.g. when they were just about to tap on som.ething)
Why not just raise the notification when the state actually changes? This way you wouldn't need to poll.
What is the "Window" you are displaying? How does it differ from the page it is replacing? Is this a popup or are you actually navigating to a different page?
What is the state that's changing? How is it changing without user interaction?
Can't you notify the user of the state change without a potentially intrusive display of a new "window"?

A: I agree with @matt-lacey, this could be dangerous and might result in a bad user experience.
With that said, this might work
 Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //navigation code here
                    });

A: I didn't know you could do a pop-up window, could you elaborate?
I've made a thread that is running at the background and making some work, if it decides that a change is necessary, I want to give the user a chance to react to it, or ignore it.
I'm pretty new to this, so if there is a better way than to navigate to a different page i would love to hear it.
Thanks.

A: It sounds to me like you want to notify the user that something has happened/changed and give them the option to do something about it, which is exactly what "toast" notifcations are all about. They pop up at the top of the screen to inform the user, and then the user can tap that toast to do something, e.g. when WiFi networks are available, you tap the toast to select an available network.
The Silverlight Windows Phone Toolkit includes the ToastRequestTrigger that you use to display toast notifications. The Windows Phone Developer Guide from the patterns & practices team gives examples of using the ToastRequestTrigger. You will need to implement the tap handling yourself in the toast content, but this should be simple enough.


text:
Q: Apache shows index of/ instead of default index html I installed apache2 on my Ubuntu 13.10 and it works without any problems. I can see the default index page (which is located in /var/www/index.html) by typing localhost/ in the address bar

Today, after I upgraded my Ubuntu to 14. 04 the localhost server doesn't work any longer and shows index of/ page instead

I have tried to reinstall everything (including php5, phpMyAdmin, and MySQL) but the problem is still there. How do I fix this?

A: You should edit the 000-default.conf file
To edit 000-default.conf you can open it in a text editor with root permission, for example:
sudo -H gedit /etc/apache2/sites-available/000-default.conf

By default DocumentRoot is as below:
DocumentRoot /var/www/html

You need to change the DocumentRoot to:
DocumentRoot /var/www/

Save the file and exit.
After this you must restart your Apache server:
sudo /etc/init.d/apache2 restart


text:
Q: Clean Project and few options are disabled in Android studio after application crash Unfortunately my android studio got crashed due to the power failure and when I restarted my android studio few options like

*

*Clean Project

*Run app

*Debug etc ., were not working properly and also disabled.

Disabled options:

Please let me know if any workaround is there

A: This might be an issue due to the crash of android studio. Please go to the "SDK manager" and select Plugins options from the left side panel and select all the plugins which were displaying with error symbol and click ok. This might solve your issue.


text:
Q: Running ghc fails with message about iOS simulator I tried running ghc to compile a haskell program, and I get the following error:
$ ghc --make main
Linking main ...
ld: building for macOS, but linking in object file built for iOS Simulator, file 'main.o' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
`clang' failed in phase `Linker'. (Exit code: 1)

Here are some details about my machine:

*

*macOS Catalina 10.15.7

*Xcode 12.2

*The Xcode developer tools were installed with xcode-select --install

*I installed ghc with brew install ghc
Some other output that might be relevant:
$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.27)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

If I run ghc --make main -v, this is what the output looks like right before it fails (apologies for the long line, not sure how to format this better):
clang -o main -fno-common -U__PIC__ -D__PIC__ -Wl,-no_compact_unwind main.o -L/usr/local/Cellar/ghc/8.10.1_2/lib/ghc-8.10.1/base-4.14.0.0 -L/usr/local/Cellar/ghc/8.10.1_2/lib/ghc-8.10.1/integer-gmp-1.0.3.0 -L/usr/local/Cellar/ghc/8.10.1_2/libexec/integer-gmp/lib -L/usr/local/Cellar/ghc/8.10.1_2/lib/ghc-8.10.1/ghc-prim-0.6.1 -L/usr/local/Cellar/ghc/8.10.1_2/lib/ghc-8.10.1/rts /var/folders/5j/wwtlv8lx0m5fmhc3hy5w5_000000gp/T/ghc49162_0/ghc_2.o -Wl,-u,_base_GHCziTopHandler_runIO_closure -Wl,-u,_base_GHCziTopHandler_runNonIO_closure -Wl,-u,_ghczmprim_GHCziTuple_Z0T_closure -Wl,-u,_ghczmprim_GHCziTypes_True_closure -Wl,-u,_ghczmprim_GHCziTypes_False_closure -Wl,-u,_base_GHCziPack_unpackCString_closure -Wl,-u,_base_GHCziWeak_runFinalizzerBatch_closure -Wl,-u,_base_GHCziIOziException_stackOverflow_closure -Wl,-u,_base_GHCziIOziException_heapOverflow_closure -Wl,-u,_base_GHCziIOziException_allocationLimitExceeded_closure -Wl,-u,_base_GHCziIOziException_blockedIndefinitelyOnMVar_closure -Wl,-u,_base_GHCziIOziException_blockedIndefinitelyOnSTM_closure -Wl,-u,_base_GHCziIOziException_cannotCompactFunction_closure -Wl,-u,_base_GHCziIOziException_cannotCompactPinned_closure -Wl,-u,_base_GHCziIOziException_cannotCompactMutable_closure -Wl,-u,_base_ControlziExceptionziBase_absentSumFieldError_closure -Wl,-u,_base_ControlziExceptionziBase_nonTermination_closure -Wl,-u,_base_ControlziExceptionziBase_nestedAtomically_closure -Wl,-u,_base_GHCziEventziThread_blockedOnBadFD_closure -Wl,-u,_base_GHCziConcziSync_runSparks_closure -Wl,-u,_base_GHCziConcziIO_ensureIOManagerIsRunning_closure -Wl,-u,_base_GHCziConcziIO_ioManagerCapabilitiesChanged_closure -Wl,-u,_base_GHCziConcziSignal_runHandlersPtr_closure -Wl,-u,_base_GHCziTopHandler_flushStdHandles_closure -Wl,-u,_base_GHCziTopHandler_runMainIO_closure -Wl,-u,_ghczmprim_GHCziTypes_Czh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Izh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Fzh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Dzh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Wzh_con_info -Wl,-u,_base_GHCziPtr_Ptr_con_info -Wl,-u,_base_GHCziPtr_FunPtr_con_info -Wl,-u,_base_GHCziInt_I8zh_con_info -Wl,-u,_base_GHCziInt_I16zh_con_info -Wl,-u,_base_GHCziInt_I32zh_con_info -Wl,-u,_base_GHCziInt_I64zh_con_info -Wl,-u,_base_GHCziWord_W8zh_con_info -Wl,-u,_base_GHCziWord_W16zh_con_info -Wl,-u,_base_GHCziWord_W32zh_con_info -Wl,-u,_base_GHCziWord_W64zh_con_info -Wl,-u,_base_GHCziStable_StablePtr_con_info -Wl,-u,_hs_atomic_add8 -Wl,-u,_hs_atomic_add16 -Wl,-u,_hs_atomic_add32 -Wl,-u,_hs_atomic_add64 -Wl,-u,_hs_atomic_sub8 -Wl,-u,_hs_atomic_sub16 -Wl,-u,_hs_atomic_sub32 -Wl,-u,_hs_atomic_sub64 -Wl,-u,_hs_atomic_and8 -Wl,-u,_hs_atomic_and16 -Wl,-u,_hs_atomic_and32 -Wl,-u,_hs_atomic_and64 -Wl,-u,_hs_atomic_nand8 -Wl,-u,_hs_atomic_nand16 -Wl,-u,_hs_atomic_nand32 -Wl,-u,_hs_atomic_nand64 -Wl,-u,_hs_atomic_or8 -Wl,-u,_hs_atomic_or16 -Wl,-u,_hs_atomic_or32 -Wl,-u,_hs_atomic_or64 -Wl,-u,_hs_atomic_xor8 -Wl,-u,_hs_atomic_xor16 -Wl,-u,_hs_atomic_xor32 -Wl,-u,_hs_atomic_xor64 -Wl,-u,_hs_cmpxchg8 -Wl,-u,_hs_cmpxchg16 -Wl,-u,_hs_cmpxchg32 -Wl,-u,_hs_cmpxchg64 -Wl,-u,_hs_atomicread8 -Wl,-u,_hs_atomicread16 -Wl,-u,_hs_atomicread32 -Wl,-u,_hs_atomicread64 -Wl,-u,_hs_atomicwrite8 -Wl,-u,_hs_atomicwrite16 -Wl,-u,_hs_atomicwrite32 -Wl,-u,_hs_atomicwrite64 -Wl,-search_paths_first -Wl,-dead_strip -lHSbase-4.14.0.0 -lHSinteger-gmp-1.0.3.0 -lHSghc-prim-0.6.1 -lHSrts -lCffi -liconv -lgmp -lm -ldl -Wl,-dead_strip_dylibs
ld: building for macOS, but linking in object file built for iOS Simulator, file 'main.o' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


text:
Q: How to do pagination of a table in Laravel? I need to implement pagination of table in Laravel. This is the code snippet I am currently using:
Controller:
  $todo = collect([
  'clientes' => ['id'=>$id, 'nombre_completo'=>$nombre_completo, 'telefono'=>$telefono, 'email'=>$email,],
  'vencimiento' => ['fin' => $vencimiento, 'inicio' => $alta, 'estado'=>$estado],
  'planes' =>$plan,
  'id'=> $nplan
]);
return view('admin.inscripciones', compact('todo'));

View:

    @for ($i = 0; $i < $todo['vencimiento']['inicio']->count(); $i++)

      {{$todo['clientes']['id'][$i]}}
      {{$todo['clientes']['nombre_completo'][$i]}}
      {{$todo['clientes']['telefono'][$i]}}
      {{$todo['planes'][$i]}}

          {{$todo['vencimiento']['fin'][$i]}}

    @endfor


text:
Q: how to display the html code on a web page that is fetched from the db? I'm using python and pyramid with mako templates on displaying web content. I have html templates that are saved in a database, and now i want to display them on a web page with styles and everything(working urls and images etc.), just like a real html page would be, but fetched from the db.
Input is something like this: general styles:
.footer-content-left {
    -webkit-text-size-adjust: 80%;
    -ms-text-size-adjust: 80%
}

img {
    height: auto;
    line-height: 100%
}

h1 a:active {color:red}

h2 a:active {color:red}

and actual content:

Awsome link

        foo.bar

 etc.

Templates are fetched and edited with a premailer like this:
template = DBSession.query(Template).filter(Template.id == '1').first()
template = transform(template.template) #editing the html code with premailer

return {'template': template}

html code is sent to mako template like this: ${template} , but end result has always been just plain text, like input in above. And code in a HTML templates is working, i'm sure about that.

A: Try: ${structure: template}, I don't know that this is an appropriate choice but http://chameleon.readthedocs.org/en/latest/reference.html#structure suggested it might.
Found here


text:
Q: Most efficient regular expression for Nginx location What is the most efficient way to define a location directive which matches something like
location = /[0-9a-zA-Z_-]{1,6} { content_by_lua_file ....}

In other words a URI which matches a string from 1 to 6 characters with "-", "_", digits and letters.
Or is it faster to check string length within my LUA code, which will generate the output by using a location directive like
location  / {content_by_lua_file...}

A: Regular expressions are very efficient at what they do.
When the task is trivial (for instance checking the presence of a particular string), a string function can be faster than a regex—depending on the platform. Here, you are checking both for a character range and a length. It's unlikely that Lua code (compiled at run time) will be faster than the pre-compiled C code of the PCRE regex library used by nginx.
In general, the regex for a string from 1 to 6 characters with "-", "_", digits and letters can be written as
^[-\w]{1,6}$

That is because

*

*The ^ anchor asserts that we are at the beginning of the string

*The \w word character matches letters, digits and the underscore character

*The $ anchor asserts that we are at the end of the string

However, in nginx, the ~ (request starts with) operator allows us to drop the beginning anchor ^. You would write something like this:
location ~ [-\w]{1,6}$ {
    # some rewrite code, for example
    # rewrite ^([^/]+)/?$ /oldsite/$1 break;
}

One more morsel of information for the curious: in Lua itself, the above regex could be turned into a Lua pattern, where % is used in place of \ to form metacharacters:
^[-%w]{1,6}$

Reference

*

*ngx_http_rewrite_module

*Lua Patterns

A: I think that in Lua you will have to check not only length, but also the content of string.
Nginx uses the C library PCRE for regular expressions.
There is also PCRE-JIT which JIT compiles regular expression, particularly useful if the regular expression is more complex than the one in your question.
I think in Nginx it's faster.