text:
Q: Do I have to block signals on the main thread to handle cancel point on another thread? When I was working on a TCP server running in a dedicated thread, I noticed strange behavior in signal handling. I have prepared the following MWE (I've used cerr to avoid race condition on debug printing):
#include <signal.h>
#include <unistd.h>

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

#undef THREAD

class RaiiObject
{
public:
    RaiiObject() { cerr << "RaiiObject ctor" << endl; }
    ~RaiiObject() { cerr << "RaiiObject dtor" << endl; }
};

static void signalHandler(int sig)
{
    write(2, "Signal\n", 7);
}

static void blockSigint()
{
    sigset_t blockset;

    sigemptyset(&blockset);
    sigaddset(&blockset, SIGINT);
    sigprocmask(SIG_BLOCK, &blockset, NULL);
}

static void setSigintHandler()
{
    struct sigaction sa;
    sa.sa_handler = signalHandler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
}

void runSelect()
{
    sigset_t emptyset;
    sigemptyset(&emptyset);

    setSigintHandler();

    RaiiObject RaiiObject{};
    fd_set fdRead;

    while (true) {
        cerr << "Loop iteration" << endl;
        FD_ZERO(&fdRead);
        FD_SET(0, &fdRead);
        while (true) {
            if (pselect(FD_SETSIZE, &fdRead, NULL, NULL, NULL, &emptyset) > 0) {
                cerr << "Select" << endl;
            } else {
                cerr << "Select break" << endl;
                return;
            }
        }
    }
}

int main()
{
    cerr << "Main start" << endl;

#ifdef THREAD
    cerr << "Thread start" << endl;
    //blockSigint();
    thread{runSelect}.join();
#else
    runSelect();
#endif

    cerr << "Main exit" << endl;

    return EXIT_SUCCESS;
}

When I compile a single-threaded program (#undef THREAD), I can correctly terminate the runSelect() function with Ctrl-C:
Main start
RaiiObject ctor
Loop iteration
^CSignal
Select break
RaiiObject dtor
Main exit

But when I compile a multithreaded (#define THREAD) program, it hangs at the signal handler:
Main start
RaiiObject ctor
Loop iteration
^CSignal

Only when I block the signal on the main thread with blockSigint() the program again work as I want.
I've examined the program with strace -tt -f and I noticed that working versions use pselect6() with ERESTARTNOHAND:
14:46:53.543360 write(2, "Loop iteration", 14Loop iteration) = 14
14:46:53.543482 write(2, "\n", 1
)       = 1
14:46:53.543586 pselect6(1024, [0], NULL, NULL, NULL, {[], 8}) = ? ERESTARTNOHAND (To be restarted if no handler)
14:46:55.286989 --- SIGINT {si_signo=SIGINT, si_code=SI_USER, si_pid=2707461, si_uid=1000} ---
14:46:55.287120 write(2, "Signal\n", 7Signal
) = 7
14:46:55.287327 rt_sigreturn({mask=[]}) = -1 EINTR (Interrupted system call)
14:46:55.287569 write(2, "Select break", 12Select break) = 12
14:46:55.287760 write(2, "\n", 1

but broken version uses futex():
[pid 3469011] 14:48:37.211792 write(2, "Loop iteration", 14Loop iteration) = 14
[pid 3469011] 14:48:37.211916 write(2, "\n", 1
) = 1
[pid 3469011] 14:48:37.212031 pselect6(1024, [0], NULL, NULL, NULL, {[], 8} <unfinished ...>
[pid 3469010] 14:48:40.046146 <... futex resumed>) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
[pid 3469010] 14:48:40.046256 --- SIGINT {si_signo=SIGINT, si_code=SI_USER, si_pid=2707461, si_uid=1000} ---
[pid 3469010] 14:48:40.046354 write(2, "Signal\n", 7Signal
) = 7
[pid 3469010] 14:48:40.046588 rt_sigreturn({mask=[]}) = -1 EINTR (Interrupted system call)
[pid 3469010] 14:48:40.046821 futex(0x7f4e5c16b9d0, FUTEX_WAIT, 3469011, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)

A:
Do I have to block signals on the main thread to handle cancel point on another thread?

You need to allow (unmask) signals in only those threads expected to handle them, and block them in others.
The OS will deliver a process-directed signal to any thread that can receive it.  Your terminal's SIGINT is sent to each process in the foreground process group, and the OS decides which thread of each will receive it.
If you only have two threads, and one of them has atomically unmasked SIGINT in a pselect while the other has SIGINT blocked, then the OS will deliver the SIGINT to the former.  If both (or neither) can handle a SIGINT, the OS will pick one of them.
Caveat: your code may "miss" a SIGINT generated when both threads have INT masked:
time  thr1        thr2
----  ----------  ------
  0   block(INT)   -
  1   run thread  (awake)    <---- SIGINT
  3   join()      pselect()
  4   ...         ...

If the signal arrives outside of thr2's pselect, the OS will find that both threads have the signal blocked.  In that case, the OS can choose whichever thread it likes for the signal to be held pending, and could choose thr1, which will never unblock.  The SIGINT will be missed.
That may be fine for your application, or it may not be.

A: As you noticed, my problem was that sigaction() has been connect signal handler to both main() thread and runSelect() thread so SIGINT signal could be caught by main().
Now I have prepared a version in which only the main thread handles SIGINT signal and sends SIGUSR1 signal to specific threads with pthread_kill().
#include <signal.h>
#include <unistd.h>

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

pthread_t nativeHandle;

class RaiiObject
{
public:
    RaiiObject() { cerr << "RaiiObject ctor" << endl; }
    ~RaiiObject() { cerr << "RaiiObject dtor" << endl; }
};

static void sigintHandler(int)
{
    write(2, "INT\n", 4);
    pthread_kill(nativeHandle, SIGUSR1);
}

static void sigusrHandler(int)
{
    write(2, "USR\n", 4);
}

static void blockSigint()
{
    sigset_t blockset;

    sigemptyset(&blockset);
    sigaddset(&blockset, SIGINT);
    sigprocmask(SIG_BLOCK, &blockset, NULL);
}

static void setSigintHandler()
{
    struct sigaction sa;
    sa.sa_handler = sigintHandler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
}

static void setSigusrHandler()
{
    struct sigaction sa;
    sa.sa_handler = sigusrHandler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGUSR1, &sa, NULL);
}

void runSelect()
{
    sigset_t emptyset;
    sigemptyset(&emptyset);

    blockSigint();
    setSigusrHandler();

    RaiiObject RaiiObject{};
    fd_set fdRead;

    while (true) {
        cerr << "Loop iteration" << endl;
        FD_ZERO(&fdRead);
        FD_SET(0, &fdRead);
        while (true) {
            if (pselect(FD_SETSIZE, &fdRead, NULL, NULL, NULL, &emptyset) > 0) {
                cerr << "Select" << endl;
                return;
            } else {
                cerr << "Select break" << endl;
                return;
            }
        }
    }
}

int main()
{
    cerr << "Main start" << endl;

    cerr << "Thread start" << endl;
    thread runSelectThread{runSelect};
    nativeHandle = runSelectThread.native_handle();
    setSigintHandler();
    runSelectThread.join();

    cerr << "Main exit" << endl;

    return EXIT_SUCCESS;
}

Main start
Thread start
RaiiObject ctor
Loop iteration
^CINT
USR
Select break
RaiiObject dtor
Main exit


text:
Q: How to use Ruby in C/C++ I have some experience in C/C++ but I am new to Ruby. So today I got a task from my teacher to use some other languages to create a shared library (in my case, .so) that I will use in my C++ program. I wanted to try Ruby for a long time, but now when I compiled, installed and played with it a bit, I have no idea what's next.
I googled alot, but all I can find (SWIG, Rice) is related to using C/C++ in Ruby, not Ruby in C/C++. Is it possible? Am I wrong with SWIG and Rice and I actually CAN use them vice-versa (ruby for c, c for ruby)? If it is so, can you please attach any guides about that?

A: Ruby is an interpreted language, and I've never seen it compiled. What I know is that you can drop into C/C++ from within ruby. It's unclear what you're trying to accomplish. You might be looking for something that doesn't exist or make sense?
In Ruby, libraries are called gems, which are a collection of classes modules and other related files.
If you're looking for information about similarities between ruby and C/C++ this might be a good starting place. https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-c-and-cpp/
Other than that, please do some more research and refine your question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why did Peeves think a ghost could become invisible? In PS (16) the Trio, headed to the Forbidden Corridor under the invisibility cloak, encounters Peeves, who hears them and says

Know you're there, even if I can't see you. Are you ghoulie or
  ghostie or wee student beastie?

and Harry decides to impersonate the Bloody Baron and answers

the Bloody Baron has his own reason for being invisible.

Now, a witch/wizard can, of course, hide through magic. What about ghosts and ghouls?
According to logic, I would say that only someone (something) physical and material can become (be made) invisible in the sense that it is not visible but is still physically there. However, on Pottermore ghosts are characterized as

transparent, three-dimensional imprint of a deceased witch or wizard,
  which continues to exist in the mortal world

and

Witches and wizards are much more susceptible to what Muggles call
  paranormal activity, and will see (and hear) ghosts plainly where a
  Muggle might only feel that a haunted place is cold or 'creepy'.
  Muggles who insist that they see ghosts in perfect focus are either a)
  lying or b) wizards showing off – and in flagrant breach of the
  International Statute of Secrecy.

So ghosts are specters that can either be seen (as pale, translucent versions of their pre-death selves) or only felt. Who is able to see them could, at most, not see them in perfect focus. Throughout the books, it appears that Peeves - similar to witches/wizards - sees them and interacts with them, as implied by Harry's answer (he presents it as an exception). Why would the poltergeist then assume that out of the blue they could not be visible to him? Wouldn't this imply that ghosts can use magic to hide (also from witches/wizards then, which would contradict the solid characterization above)?
And why should ghouls be invisible? They have a corporeal appearance and have no magic powers.
Of course, it could be that Peeves asks the question this way simply because he can't see anybody in the dark of the night but given Harry's answer and the fact that Peeves believes him, the issue as pertains to ghosts remains. I'm curious if there is a good explanation other than assuming Peeves is stupid or too scared of the Bloody Baron to question Harry's answer.

A: Not sure what Peeves was thinking in that precise scene.
However, in PoA we see Harry in the invisibility cloak scaring Malfoy and his goons (after he sneaks into Hogsmeade) by hurling mud at him, who thinks it's possibly the invisible ghosts supposedly haunting the Shrieking Shack.
Although they live in a world full of magic where randomly flying objects should be an everyday occurrence, or, at least not something strange, the fact that Malfoy was scared it might be invisible ghosts suggests that ghosts or possibly other evil spirits becoming invisible is not something unheard of, in the Harry Potter Universe.
Thus it's not strange that Peeves believed the Baron had turned invisible.

A: Ghosts can at the very least hide themselves out of sight.
There's no canon information I've found about whether ghosts can actually become invisible. However, they certainly can hide. Moaning Myrtle was able to hide from the Prefects to spy on them unnoticed in the bathrooms. It's unclear whether she made herself invisible to do this or if she just hid, but it doesn't seem like anyone noticed her there.

"Have you been spying on him, too?' said Harry indignantly. 'What d'you do, sneak up here in the evenings to watch the Prefects take baths?'
'Sometimes,' said Myrtle, rather slyly, 'but I've never come out to speak to anyone before." - Harry Potter and the Goblet of Fire, Chapter 25 (The Egg and the Eye)

People usually avoided Myrtle, and would even more want to avoid her if they knew she'd be peeping at them in the bath. The girls' bathroom Myrtle was hardly in use because of her presence, but the Prefects' bathroom didn't seem to have this same problem. We know she spied on Cedric, and Cedric wouldn't have likely known this and let Harry use there without warning. He wouldn't have noticed her presence, however it is that she'd hidden, so ghosts are provably capable of not being noticed. Peeves doesn't seem to have any extrasensory perception, so he might not automatically know the difference between a well-hidden ghost and an invisible one.
Ghosts may be able to become invisible, but it's not clear.
It seems at least possible that ghosts can become invisible. It's never said explicitly that they can, but it is mentioned, however, that Peeves (and possibly poltergeists in general) can turn invisible.

"Nearly Headless Nick was always happy to point new Gryffindors in the right direction, but Peeves the poltergeist was worth two locked doors and a trick staircase if you met him when you were late for class. He would drop waste-paper baskets on your head, pull rugs from under your feet, pelt you with bits of chalk or sneak up behind you, invisible, grab your nose and screech, 'GOT YOUR CONK!" - Harry Potter and the Philosopher's Stone, Chapter 8 (The Potions Master)

However, the J.K. Rowling Pottermore writing on Peeves says poltergeists are by nature invisible, and they certainly aren't ghosts - so this isn't proof ghosts can as well, but is notable as they're somewhat similar.


text:
Q: Access an individual element of a Perl 2x2 array I am able to create a matrix using this code
#!/usr/bin/perl -w

@arr1 = (10,20,30);
@arr2 = (10,20,30);
@arr3 = (10,20,30);
@ref_arr = (\@arr1, \@arr2, \@arr3);

print"Prog starts\n";

foreach $ref (@ref_arr) {
  #print @$ref->[0];
  foreach $val (@$ref) {
    print "$val ";
  }
  print"\n";
}

Using the map function I can modify each value in the matrix like this
Example: increase every value by 1
foreach $ref (@ref_arr) {
  map($_++, @$ref);
}

but I want to modify a certain row or a specific value, i.e. either add 1 to all of the second row's values or to the first column of the second row

A: Are you using row x column or column x row? I will assume the first.
To modify the value at $x, $y:
$ref_arr[$x][$y] = $new_value;

To add 1 to column $x:
$_++ for @{ $ref_arr[$x] };

To add 1 to row $y:
$_->[$y]++ for @ref_arr;

A: You must always use strict and use warnings at the top of every program that you write. This applies especially if you are asking for help with your code, as these measures will reveal simple errors that you would otherwise overlook
The map function is not for iterating over a list: it is for 'mapping' one list to another by applying a function to each element of the source list
When you write
map($_++,@$ref)

you are building and discarding a copy of the values in @list. What you should write is
$_++ for @$ref

As for how to modify a single value out of the array, your array initialisation can be simplified to
my @data = (
    [10, 20, 30],
    [10, 20, 30],
    [10, 20, 30]
)

I hope from this it is easier to see that the first 10 in the structure is accessible as $data[0][0] and, say, the last 20 is $data[2][1] (remembering that Perl arrays are indexed from zero). You can access and modifiy these values just as any ordinary scalar
As for your particular examples, the second row is @{$data[1]} so you can increment every element of the row by writing $_++ for @{$data[1]}. The first column of the second row is incremented with $data[1][0]++


text:
Q: duplicate weblogic domain from solaris 9 command line I need to search for a string of characters in a weblogic domain and then replace that string with a new one. I tried doing a grep -r but solaris 9 doesn't support it. I tried a find command:
find <mydir>-type f -exec sed -i 's/string1/string2/g' {}+ .

This did not work.
I have multiple directory names, file names and file content to change.
I am essentially coping a weblogic domain, tar and zipping it, moving it, unzip, untar, rename and reconfig and then launch. all from command prompt.
ANY help would be very much appreciated.

A: -i is a GNU sed extension.
Here is one way to achieve what you want with Solaris 9 commands :
find <mydir> -type f -exec ksh -c '
    for i do sed "s/string1/string2/g" $i > /tmp/foo && cat /tmp/foo > $i; done' ksh {} +

A: Thanks guys but i found my answer:
find . -type f -exec grep -l <search string> {} \; | while read i; do perl -pi -e 's/<string1>/<string2>/g' $i;done

Thanks for the replies.


text:
Q: Fragment (ScrollView) Covering Bottom NavView Items I have a Fragment with a ScrollView and a BottomNavBar from which the Fragment is inflated but when compiled the ScrollView cover the Bottom Nav Bar making is unusable how do I restrict the content of the Fragment to only the rest of the screen leaving the bottom navbar as it is.
BottomNav Bar Activity Code
    <?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/landing_page_body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".pages.LandingPage"
    tools:openDrawer="start">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_gravity="bottom"
            android:transformPivotX="100dp"
            app:labelVisibilityMode="unlabeled"
            app:menu="@menu/bottom_navbar_menu"

            app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/side_navbar_header"
        app:menu="@menu/side_navbar_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

Fragment xml Code
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:isScrollContainer="false">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".fragments.auction_add">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="40dp"
            android:layout_marginRight="20dp"
            android:layout_marginBottom="5dp"
            android:paddingTop="20dp"
            android:text="Enter Auction Details -"
            android:textSize="40dp"></TextView>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingVertical="5dp">

            <ImageView
                android:layout_width="200dp"
                android:layout_height="200dp"></ImageView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="5dp"
            android:gravity="center"
            android:paddingHorizontal="15dp"
            android:paddingVertical="5dp">

            <EditText
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:layout_gravity="end"
                android:background="@drawable/rounded_edittext"
                android:gravity="center"
                android:hint="Name of Item"
                android:maxLines="1"
                android:overScrollMode="ifContentScrolls" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingHorizontal="20dp"
            android:paddingVertical="5dp">

            <EditText
                android:layout_width="300dp"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:background="@drawable/rounded_edittext"
                android:gravity="center"
                android:hint="Description"
                android:maxLength="40"
                android:maxLines="5"
                android:minHeight="100dp"
                android:overScrollMode="ifContentScrolls"
                android:padding="5dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingVertical="5dp">

            <EditText
                android:layout_width="300dp"
                android:layout_height="50dp"

                android:background="@drawable/rounded_edittext"
                android:gravity="center"
                android:hint="Initial Price"
                android:maxLines="1"
                android:overScrollMode="ifContentScrolls" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingVertical="5dp">

            <EditText
                android:id="@+id/startTimePicker"
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:background="@drawable/rounded_edittext"
                android:gravity="center"
                android:hint="Start Time"
                android:maxLines="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingVertical="5dp">

            <EditText
                android:id="@+id/endTimePicker"
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:background="@drawable/rounded_edittext"
                android:gravity="center"
                android:hint="End Time"
                android:maxLines="1" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginVertical="30dp"
            android:gravity="center"
            android:paddingVertical="5dp">

            <Button
                android:layout_width="200dp"
                android:layout_height="50dp"
                android:background="@drawable/rounded_edittext"
                android:text="Post Item" />

        </LinearLayout>

    </LinearLayout>
</ScrollView>

Output -
Final Result of Above XML

A: Add this below code in the bottom of parent linearlayout in Fragment xml Code
 <View
    android:layout_width="match_parent"
    android:layout_height="80dp">

</View>

Hope it will work...


text:
Q: How can I assign a value to a variable by passing a string of its name? Example:
int XValue;
int YValue;

void AssignValue(string VariableName,int VariableValue)
{
    VariableName = VariableValue;
}

void CallAV()
{
    AssignValue("XValue", 10);
    AssignValue("YValue", 15);

}

So, basically i want to change the value of a variable by knowing its name.

A: What you're looking for is collectively called Reflection. Specifically, you want to use Type.GetField(). You could do something like this:
void AssignValue(string VariableName, int VariableValue)
{
    // Get the non-public instance variable (field)
    FieldInfo field = GetType().GetField(VariableName, BindingFlags.NonPublic | BindingFlags.Instance);

    // Set the variable's value for this instance of the type
    field.SetValue(this, VariableValue);
}


text:
Q: c# how to measure used memory from referenced method I've written a program that splits an XML into a lot of smaller XMLs and for performance reasons this program keeps all XML writers open at the same time and calls the relevant methods recursively. Also all this is nested in zip and xml readers and writers. When a lot of writers are open at the same time a stackoverflow exception happens and since these can't be caught I try to throw an exception in my code if too much memory is used. This works fine as a stand-alone application, but the used memory is reported incorrectly from the same method when used as a reference.
I wrote the following code that is called each recursion:
            var performance = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            var available = performance.NextValue()/10;
            var memory = 0.0;

            using (Process proc = Process.GetCurrentProcess())
            {
                memory = proc.PrivateMemorySize64 / (1024 * 1024);
            }

            if(memory / available > maxMemoryUsageFactor)
            {
                throw new Exception("Memory usage is too high.");
            }

This seems to do the trick when I run the program as a application. Typically on my workstation I will get a value of 328 MB for available memory (please note that I devide the MB as gotten from PerformanceCounter by 10, which makes it correpond with the debugger from Visual Studio, but is kinda odd). For maxMemoryUsageFactor I use 0.8, so that I can do a safe rollback of all the streams.
However, the code is intended to be used as a reference (.dll) in another application, and when I use it as such it seems be able to use roughly the same amount of memory, but only reports the memory used by the main application, not by the referenced method. At the point where it normally will report about 75% of memory usage, none of the metrics available in the process reports over 30%:

Initiating Chained writer 964 of 964 | current memory (MB): 58 of 300,9(19,2755072038829%) |  PagedMemorySize64:58 NonpagedSystemMemorySize64:0 VirtualMemorySize64:4709 WorkingSet64:69 PagedSystemMemorySize64:0 PeakPagedMemorySize64:58

I assume that this has something to do with either the accessibility of the memory used by the reference (since Visual studio also shows only about 60MB in it's performance chart now and in the stand alone version 328MB), or lag in memory reporting, but I have no idea how and why.


text:
Q: Ionic2,Angular2: How to hide the content under the keyboard on a device when keyboard pops out? I tried to debug my app on an android device but I came across this weird problem that the keyboard which pops on clicking an input field pushes the whole page content(including the tabs at the bottom) to the top along with it. I might be missing out something silly. Kindly help me. I've gone through many links which were not very clear and a few were not working.
https://github.com/driftyco/ionic/issues/7047
https://github.com/driftyco/ionic/issues/5432
https://forum.ionicframework.com/t/ionic-2-ion-content-height-dynamically-changes-while-showing-keyboard-on-device/46360
This is my html file:
<ion-header>
<ion-navbar>

    <button ion-button>
  <ion-icon name="menu"></ion-icon>
</button>
</ion-navbar>

        <ion-item>
            <ion-input type="text" placeholder="Enter Keyword" [(ngModel)]="searchText" (ngModelChange)="textChanged($event)"> </ion-input>
        </ion-item>
        <ion-item>
            <ion-label> Branch</ion-label>
            <ion-select>
                <ion-option *ngFor="let branchObj of Branches" [value]="branchObj">
                    {{branchObj.name}}
                </ion-option>
            </ion-select>
        </ion-item>
        <ion-item>
            <ion-label>Subject</ion-label>
            <ion-select>
                <ion-option *ngFor="let subjectObj of subjects" [value]="subjectObj">
                    {{subjectObj.name}}
                </ion-option>
            </ion-select>
        </ion-item>
        <ion-item>
            <ion-label>
                Type of Course
            </ion-label>
            <ion-select>
                <ion-option *ngFor="let course of Courses" [value]="course">
                    {{course.choicetext}}
                </ion-option>
            </ion-select>
        </ion-item>
        <button class="button" type="submit" (click)="submitSearch()" ion-button full> Search </button>

{{message}}

This is my scss file:
page-search {
color: white;
.inner {
    margin: auto;
    width: 90%;
    height: 50%;
    padding-top: 35px;
    // padding-bottom: 0px;
}
.item-select {
    font-size: 15px;
    width: 100%;
    height: 25%;
    margin: 15px auto;
    border-radius: 5px;
}
.item-input {
    width: 100%;
    height: 25%;
    margin: 15px auto;
    border-radius: 5px;
}
.button {
    height: 30%;
    background: red;
    width: 30%;
    margin: auto;
    text-align: center;
    border-radius: 5px;
}
.alert-radio-label {
    white-space: normal!important;
}
.titleicon {
    position: absolute;
    width: 100%;
    left: 0;
    bottom: 0;
    text-align: center;
}
.bottomitems {
    padding-bottom: 20px;
    padding-top: 20px;
    margin: auto;
}
.item-divider {
    background-color: #535A5E;
    color: white;
}

Kindly provide me with a solution. Thanks in advance.


text:
Q: Session value is changing during the execution of code I am working in an asp.net project.
I am storing values to session during the Page_Load in a Master Page. I am accessing these values in a Web-UserControl, which is placed in the template page (which inherits from the MasterPage).
Now the issue is i am not getting the session values in the user control properly.
While i executed the code in debug mode i came to know that i am getting the session value at the beginning of the function, but the value is being cleared at the end of the function. This is an absurd situation.
Have anyone faced this kind of issues?
Can anyone help me in solving this issue?


text:
Q: Reference for phClr in openxml I am trying to find value for phClr, but no results.
Slide master is not having mapping for phClr.
I am aware that phClr is just a passed-in color value, but what exactly is its color reference?
Is it bg2 or anything else?

A: http://msdn.microsoft.com/en-us/library/cc964302(v=office.12).aspx

Blockquote
  The scheme color value is set to placeholder color (the value phClr). This value appears throughout the fill, line, effect, and background styles and indicates that the settings are applied to the theme color applicable for a given style. This allows the same fill, line, and effect styles to populate across the theme colors that appear in the OfficeArt galleries.

"phClr" is a kind of placeholder color


text:
Q: How to access kubernetes keys in etcd Question
How to get the Kubernetes related keys from etcd? Tried to list keys in etcd but could not see related keys. Also where is etcdctl installed?
$ etcdctl
bash: etcdctl: command not found..

$ sudo netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:2379          0.0.0.0:*               LISTEN      386/etcd
tcp        0      0 127.0.0.1:2380          0.0.0.0:*               LISTEN      386/etcd

$ curl -s http://localhost:2379/v2/keys | python -m json.tool
{
    "action": "get",
    "node": {
        "dir": true
    }
}

Background
Installed Kubernetes 1.8.5 by following Using kubeadm to Create a Cluster on CentOS 7. When I looked at Getting started with etcd, v2/keys looks to be the end point.

A: Usually you need to get etcdctl by yourself. Just download the latest etcdctl archive from etcd releases page.
Also, starting from Kubernetes version 1.6 it uses etcd version 3, so to get a list of all keys is:
ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 get / --prefix --keys-only

You can find all etcdctl v3 actions using:
ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 --help

EDIT (thanks to @leodotcloud):
In case ETCD is configured with TLS certificates support:
ETCDCTL_API=3 etcdctl --endpoints <etcd_ip>:2379 --cacert <ca_cert_path> --cert <cert_path> --key <cert_key_path> get / --prefix --keys-only

A: For Minikube
(v1.17.0)
You can see the arguments exploring the pod: kubectl describe pod -n kube-system etcd-PODNAME |less
Here you can see the certificates path and much more.
To fastly query your etcd dictionary you can use this alias:
alias etcdctl_mini="MY_IP=$(hostname -I |awk '{print $1}'|tr -d ' '); \
    ETCDCTL_API=3; \
    sudo -E etcdctl --endpoints ${MY_IP}:2379 \
    --cacert='/var/lib/minikube/certs/etcd/ca.crt' \
    --cert='/var/lib/minikube/certs/etcd/peer.crt' \
    --key='/var/lib/minikube/certs/etcd/peer.key'"

$ etcdctl_mini put foo bar

A: Access the docker container, and run the following commmand:
ETCDCTL_API=3 etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/server.crt --key /etc/kubernetes/pki/etcd/server.key get / --prefix --keys-only

A: I needed to use etcdctl with etcd installed on CoreOS (Container Linux).
In my case the following worked (executed from CoreOS shell prompt):
$ sudo ETCDCTL_API=3 etcdctl --cacert /etc/ssl/etcd/etcd/peer-ca.crt --cert /etc/ssl/etcd/etcd/peer.crt --key /etc/ssl/etcd/etcd/peer.key get --prefix / --keys-only

I used sudo as a quick solution to the permission problem "Error: open /etc/ssl/etcd/etcd/peer.crt: permission denied".

A: You can also try following (assuming etcd pod name is etcd-minikube).
Minikube access using etcdctl was already explained above.
$kubectl -it exec etcd-minikube -n kube-system -- etcdctl --cacert='/var/lib/minikube/certs/etcd/ca.crt' --cert='/var/lib/minikube/certs/etcd/peer.crt' --key='/var/lib/minikube/certs/etcd/peer.key' put foo bar

OK
$kubectl -it exec etcd-minikube -n kube-system -- etcdctl --cacert='/var/lib/minikube/certs/etcd/ca.crt' --cert='/var/lib/minikube/certs/etcd/peer.crt' --key='/var/lib/minikube/certs/etcd/peer.key' get foo

foo
bar


text:
Q: List all possible actions on a 4x4 board in Prolog How can I list all possible boards after (for example) one player performs some action in a 4x4 board (with 8 different pions)?
The pions should be, for example:
([1,2,3,4,5,6,7,8])

and each time you play one automatically it cannot re-used.
The board should be like this board
([1,1,-,-],(1,2,-,-)...(1,3,-,-)(1,4,-,-)
 [2,1,-,-],(2,2,-,-)...(2,3,-,-)(2,4,-,-)
 [3,1,-,-],(3,2,-,-)...(3,3,-,-)(3,4,-,-)
 [4,1,-,-],(4,2,-,-)...(4,3,-,-)(4,4,-,-)

And one player per round puts one pion on the board until it's full.

A: I assume you have a predicate like board0_move_board/3, which is a ternary relation between a board B, a move M, and the resulting board after the move M is made on B. Further, I assume you have a predicate board_move/2 that relates a board to a move that is possible on that board, and on backtracking successively gives all moves that are possible. With these predicates, you can get all possible boards with:
findall(Board, (board_move(Board0, Move), board0_move_board(Board0, Move, Board)), Boards)


text:
Q: jQuery ui dialog box appears off view port I am using jQuery ui dialog, when the page height is longer that view port height, vertical scroll bar will appear, then, when user scroll the page, the dialog will get off view port area ..
Is there an option to make the dialog always within the viewport area no matter the scroll offset is?

A: Position:fixed; Might be what you are looking for.


text:
Q: Reading created record type from file in pascal I'll try to be the shortest possible.
I have these DATA TYPES in my program.'
type
  pha = (SenoraBlanco, SenorVerde, SenoraCeleste, ProfesorCiruela,
    SenoritaEscarlata, CoronelMostaza, Biblioteca, Cocina, Comedor, Estudio,
    Vestibulo, Salon, Invernadero, SalaDeBaile, SalaDeBillar, Candelabro,
    Cuchillo, Cuerda, LlaveInglesa, Revolver, Tubo);

  a = Candelabro..Tubo;
  h = Biblioteca..SalaDeBillar;
  p = SenoraBlanco..CoronelMostaza;

  sbr = record
    arma: a;
    habt: h;
    prj: p;
  end;

var
  game: text;
  sobre: sbr;

And I want to read this line from a file and then assign it to fields of the variable sobre, type sbr:
CoronelMostaza Candelabro Vestibulo
Essentially this is what I'm trying:
sobre.prj  := CoronelMostaza;
sobre.arma := Candelabro;
sobre.habt := Vestibulo;

And this is what I've tried so far:
ReadLn(game, sobre.prj, sobre,arma, sobre.habt);

I'd tried turning off the IO check with no result, the closest I've got to the answer of this problem is assign the first word to the first variable, but always end in either an error or empty variables. Please help me and if you will, give me an idea of what's happening behind all this!

A: Assuming the text file contains the type literals of type pha.
Declare a a text constant containing those literals:
const
  phaStr : array[pha] of string = ('SenoraBlanco', 'SenorVerde', 'SenoraCeleste', 'ProfesorCiruela',
    'SenoritaEscarlata', 'CoronelMostaza', 'Biblioteca', 'Cocina', 'Comedor', 'Estudio',
    'Vestibulo', 'Salon', 'Invernadero', 'SalaDeBaile', 'SalaDeBillar', 'Candelabro',
    'Cuchillo', 'Cuerda', 'LlaveInglesa', 'Revolver', 'Tubo');

To get an integer index of one of those string literals:
function IndexOfPhaStr( const aStr : string) : integer;
var
  aPHA : pha;
begin
  Result := -1;
  for aPHA := Low(pha) to High(pha) do
  begin
    if (aStr = phaStr[aPHA]) then
    begin
      Result := Ord(aPHA);
      break;
    end;
  end;
end;

The file contains text information, so you will have to translate the text into your data types.
A simple example using TStringList in classesh.inc:
var

  i : Integer;
  sList : TStringList;
  s : String;
  ix : array [1..3] of integer;
begin
  ...
  sList := TStringList.Create;
  sList.Delimiter := ' ';
  AssignFile(game,'TEST.Txt');
  Reset(game);
  System.ReadLn(game, s);
  System.CloseFile(game);
  sList.DelimitedText := s;
  for i := 0 to 2 do
    ix[i+1] := IndexOfPhaStr(sList[i]);
  if (ix[1] in [Ord(Low(p))..Ord(High(p))])
    then sobre.prj := pha(ix[1]);
  if (ix[2] in [Ord(Low(a))..Ord(High(a))])
    then sobre.arma := pha(ix[2]);
  if (ix[3] in [Ord(Low(h))..Ord(High(h))])
    then sobre.habt:= pha(ix[3]);
  sList.Free;
end;

If your text file contains more information, do a text conversion for them as well.
PS. I'll leave the error handling as an exercise.


text:
Q: Is this the expected behavior of firestore increments inside transactions? EDIT: Turns out there is a bug in my code and nothing wrong with the SDK. There is no problem in using two or more atomic increment operations on the same document in the same transaction. For more context read the accepted answer and its comments.

I'm using firestore to count how many users are there in my users collection depending on their childrenSituation field value. This field can be HAS_KIDS, DOESNT_HAVE_KIDS or PERIODICALLY_HAS_KIDS.
To do so, I have a data document in a collection called aggregated. This document has three numeric fields which I increase or decrease whenever I create or delete a user by using an atomic increase. But when it comes to updating a user I have to update two numeric values in the same document in the same transaction, which results in setting one of the fields to -1 instead of reducing it in one unit, and not setting the other to any value.
I do this with the increment FieldValue like so:
async updateUser(user: User, userChildrenSituationBeforeUpdate: ChildrenSituationEnum): Promise<void> {
    return await this._firestore.runTransaction(async (t) => {
      const userDocSnap = await t.get(this._usersCollection.doc(user.id));
      const aggregatedDataDocSnap = await t.get(this._agregateDataCollection.doc('data'));

      t.set(userDocSnap.ref, this._serializer.serializeUser(user), {merge: true});
      t.update(aggregatedDataDocSnap.ref, {
        [user.childrenSituation]: this._admin.firestore.FieldValue.increment(1),
        [userChildrenSituationBeforeUpdate]: this._admin.firestore.FieldValue.increment(-1),
      });
    });
  }

I pass the updated user and the previous childrenSituation to this method [I did it to save a read, but I see now that it's unnecessary as I'm fetching the user doc from the DB]. To update the user, I "serialize" it because Firestore can't take class instances directly and update the document. For the aggregated document, I update both fields using an atomic increase: one is positive and the other is negative.
The expected behavior
In my units tests, I create a user in the pretest and so this is the content of the aggregated/data document before calling the updateUser method:
{
    DOESNT_HAVE_KIDS: 1,
}

Then updateUser is called and I expected the contents of aggregated/data to be:
{
    HAS_KIDS: 1,
    DOESNT_HAVE_KIDS: 0
}

What actually happened
With the same pretest conditions I mentioned, the contents of aggregated/data after executing updateUser are:
{
    DOESNT_HAVE_KIDS: -1
}

Is this the expected behavior for Firestore, or should I open an issue in github? If Firestore is not compatible with having more than one atomic increase in the same write operation, at least it should set it to 0. Right?

A: It's difficult to exactly understand what happens with your code because we cannot reproduce the exact same situation (we only see one function).
However, I've done a test with a simple HTML page, JavaScript and the JS SDK (not TypeScript and not the Admin SDK) and it seems to works correctly:

*

*Firestore Transaction can execute several writes in one atomic operation, as explained in the doc;

*If the field does not exists in the aggregated/data document it is correctly created with the correct value (i.e. 1 in case of increment on a non-existing field or -1 in case of decrement on a non-existing field).

You can open the following HTML page locally in a browser and test it and find what to potentially change in your code. I've just wrote dummy date to the user doc as I don't really understand what you do with this._serializer.serializeUser(user). You need to adapt the config object to your Firebase project.
Note that you don't need to fetch the docs in order to get their DocumentReference: So no need to do const userDocSnap = await t.get(...) and then userDocSnap.ref. Just do t.set(this._usersCollection.doc(user.id), this._serializer.serializeUser(user), {merge: true}); since you already know the DocumentReference of this doc. Same for aggregatedDataDocSnap: no need to fetch the doc.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test SO</title>

    <script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.2.5/firebase-firestore.js"></script>

    <script>
      // Initialize Firebase
      var config = {
        projectId: '......',
      };

      firebase.initializeApp(config);
      const db = firebase.firestore();

      async function updateUser(user, userChildrenSituationBeforeUpdate) {
        return await db.runTransaction(async (t) => {
          t.set(
            db.collection('users').doc(user.id),
            { foo: 'bar' },
            { merge: true }
          );
          t.update(db.collection('aggregated').doc('data'), {
            [user.childrenSituation]: firebase.firestore.FieldValue.increment(
              1
            ),
            [userChildrenSituationBeforeUpdate]: firebase.firestore.FieldValue.increment(
              -1
            ),
          });
        });
      }

      updateUser({ id: '2', childrenSituation: 'HAS_KIDS' }, 'DOESNT_HAVE_KIDS')
        .then(() => {
          console.log('OK');
        })
        .catch((error) => {
          console.log(error);
        });
    </script>
  </head>
  <body></body>
</html>


text:
Q: How to create custom form validator in 2 input? i want to validate that one input number is always greater to one another How to create custom form validator in 2 input? I want to validate that one input number is always greater to another one.
  ValidateMaxMin(control: FormControl) {
    console.log(control.value.productMin);
    if (control.value.productMin != 0) {
      return { hasError: true };
    }
    return null;
  }

 this.productForm = this.fb.group ({ //form validator for create and update
      '_id': [ "" ],
      'productName': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Z\s]*$/), Validators.minLength(1), Validators.maxLength(50)]) ],
      'supplierId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'brandId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'categoryId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'productPrice': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productQuantity': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productMax': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productMin': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(0), Validators.max(99999), this.ValidateMaxMin ]) ],

    });

In above code, I can only validate one specific field, whereas my intention is to specify/get two fields and compare them.

A: Here is the validation method that will do what you want
static ValidateMaxMin(firstField: FormControl | AbstractControl | null,
                      secondField: FormControl | AbstractControl | null,
                      message = `one input number should alwasy be greater than another`
): ValidatorFn {
return (): ValidationErrors | null => {
  if (firstField && secondField && firstField.value >= secondField.value) {
    const notGreater = { notGreater: { message: message } };
    secondField.setErrors(notGreater);
    return notGreater;
  }
  notGreater!.setErrors(null);
  return null;
};

}
and an example how you can use it in your forms
this.form = this.fb.group({
  firstField: ['', Validators.required],
  secondField: ['', Validators.required],
});
this.form.setValidators(Validators.passwordConfirming(this.form.get('password'), this.form.get('passwordConfirm')));


text:
Q: How can I install BeautifulSoup? I keep getting "No module named bs4" When I try to import Beautifulsoup
import bs4

I keep getting the error
ImportError: No module named bs4

I have tried to address this by trying all of the following (individually and together) with Python 3 and have had no success. What's going wrong?
sudo pip3 install beautifulsoup4
sudo apt-get install python3-bs4

A: The following approach appears to be working:
sudo pip3.6 install bs4

from bs4 import BeautifulSoup


text:
Q: How do I get my Ubuntu laptop's display on the ubuntu desktop connected to the network? My network consists of an ubuntu laptop and an ubuntu desktop connected via a router. Now, I want to work on my laptop and see the output on the desktop screen, through the network. How do I achieve this? Thanks.

A: There are two ways of doing this. You can either share your entire desktop (VNC), or you can run software on the server and have them displayed on your laptop (SSH).
A. VNC
You will need to install a VNC server on the desktop and client on your laptop. I believe that recent versions of Ubuntu have vino (client) and vinagre (server) preinstalled. So, follow these steps on the server (source):

*

*On the server, search for "Remote Desktop" in the menu and open it:

*Tell it to allow other users to view and control your desktop and choose a password:

*On the client, run "Remote Desktop Viewer", you should be able to see and connect to your desktop:

There are other VNC client/server combinations you can try if this one is not good enough for you. See here.
B. ssh
There is also a simpler way of doing this by connecting over ssh.

*

*Install the ssh package on both client and server
 sudo apt-get install ssh

*Login to your server using X11 forwarding (-Y or -X)
 ssh -Y user@server

*You are now connected to your server. If you run a graphical application, it will be displayed on your local machine. For example, running gimp will cause gimp to be started on your desktop machine and be displayed on you laptop's screen.


text:
Q: Cannot display all the data of the same session user in PHP The problem is when I start a session and I want to display all the data of the current session user is that only one data is fetch from the database. But when I put the session_start along with the table, I cannot access the echo username.
<?php
session_start();
if(!isset($_SESSION["uname"]))
{
 header("location:userdash.php");

}else{

                include('db.php');
                $sql ="Select * from poolreservation where uname ='".$_SESSION['uname']."'";
                $re = mysqli_query($con,$sql);
                while($row=mysqli_fetch_array($re))
                {
                    $id = $row['id'];
                    $resortname = $row['resortname'];
                    $hourstay = $row['hourstay'];
                    $addon = $row['add on'];
                    $cin = $row['cin'];

                }
}

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Reservation History</title>
    <link rel="icon" type="text/css" href="image/icon/history.png">

              RESERVATION HISTORY

                      #
                      Name of resort
                      Hour of stay
                      Add-on
                      Date

                        <?php echo $id; ?>
                        <?php echo $resortname; ?>
                        <?php echo $hourstay; ?>
                        <?php echo $addon; ?>
                        <?php echo $cin; ?>

I expect that it displays all of his/her data, I'm working on a transaction history btw.


text:
Q: Can't load shinobicharts-android from loader I'm trying to test out the ShinobiCharts for Android library. I have included the library folder as a project dependency (I'm on Intellij), and all the relevant classes (e.g. ShinobiChart, ChartFragment, etc) compile just fine. But when I run the project, I get the following error: java.lang.UnsatisfiedLinkError: Couldn't load shinobicharts-android from loader dalvik.system.PathClassLoader. I don't understand how the libraries can compile fine but then fail at runtime. Any ideas?

A: Solution: for both IntelliJ and Eclipse, ignore the instructions provided by ShinobiCharts for adding the library as a project, or adding a Jar to the build path, etc. Instead, navigate to the libs folder in the ShinobiCharts download (i.e. shinobichart-android-library/libs), and then do either: (a) if you already have a libs folder, copy the contents of this folder (i.e. not the folder itself) into the libs folder inside your project; or (b) if you don't have a libs folder in the project already, just copy the entire libs folder into your project. Only then will Intellij/Eclipse figure out where the files are at runtime.


text:
Q: How do you call python command "workon" from PHP exec? I am running a PHP script from the CLI. In that PHP script I would like to execute a few commands from the command line using system(). Perhaps this isn't the right tool for the job, and I could probably just wrap the PHP script in a shell script, but I want to know if it's possible to do completely within the PHP script.
When I do this in a terminal it works fine:
user@host:~$ workon pootle
(pootle)user@host:~$

However this doesn't work from PHP (being executed as the same user).
#!/usr/bin/env php
<?php
system('workon pootle'); // sh: 1: workon: not found
system('/bin/bash workon pootle'); // /bin/bash: workon: No such file or directory
system('/bin/sh workon pootle'); // /bin/sh: 0: Can't open workon

I notice that the output for the last two is exactly the same as when executing by a terminal, but the first one is different. I thought it might be an alias, however it doesn't appear to be. alias | grep -i workon shows no output.
I also compared all of the environment variables returned from command line env and PHP system('env'), and all but _ are exactly the same, including SHELL=/bin/bash.
The output of which workon executed by the terminal is empty.
Edit
Maybe I'm getting somewhere with this.
user@host:~$ type workon
workon is a function
workon ()
{
    typeset env_name="$1";
    if [ "$env_name" = "" ]; then
        lsvirtualenv -b;
        return 1;
    fi;
    virtualenvwrapper_verify_workon_home || return 1;
    virtualenvwrapper_verify_workon_environment $env_name || return 1;
    activate="$WORKON_HOME/$env_name/$VIRTUALENVWRAPPER_ENV_BIN_DIR/activate";
    if [ ! -f "$activate" ]; then
        echo "ERROR: Environment '$WORKON_HOME/$env_name' does not contain an activate script." 1>&2;
        return 1;
    fi;
    type deactivate > /dev/null 2>&1;
    if [ $? -eq 0 ]; then
        deactivate;
        unset -f deactivate > /dev/null 2>&1;
    fi;
    virtualenvwrapper_run_hook "pre_activate" "$env_name";
    source "$activate";
    virtualenvwrapper_original_deactivate=`typeset -f deactivate | sed 's/deactivate/virtualenv_deactivate/g'`;
    eval "$virtualenvwrapper_original_deactivate";
    unset -f deactivate > /dev/null 2>&1;
    eval 'deactivate () {

        # Call the local hook before the global so we can undo
        # any settings made by the local postactivate first.
        virtualenvwrapper_run_hook "pre_deactivate"

        env_postdeactivate_hook="$VIRTUAL_ENV/$VIRTUALENVWRAPPER_ENV_BIN_DIR/postdeactivate"
        old_env=$(basename "$VIRTUAL_ENV")

        # Call the original function.
        virtualenv_deactivate $1

        virtualenvwrapper_run_hook "post_deactivate" "$old_env"

        if [ ! "$1" = "nondestructive" ]
        then
            # Remove this function
            unset -f virtualenv_deactivate >/dev/null 2>&1
            unset -f deactivate >/dev/null 2>&1
        fi

    }';
    virtualenvwrapper_run_hook "post_activate";
    return 0
}

A: bash /usr/share/virtualenvwrapper/virtualenvwrapper.sh workon
I found this by installing virtualenvwrapper and then i ran
 env | grep VIRTU
VIRTUALENVWRAPPER_PROJECT_FILENAME=.project
VIRTUALENVWRAPPER_SCRIPT=/usr/share/virtualenvwrapper/virtualenvwrapper.sh
VIRTUALENVWRAPPER_HOOK_DIR=/root/.virtualenvs
_VIRTUALENVWRAPPER_API= mkvirtualenv rmvirtualenv lsvirtualenv showvirtualenv workon add2virtualenv cdsitepackages cdvirtualenv lssitepackages toggleglobalsitepackages cpvirtualenv setvirtualenvproject mkproject cdproject mktmpenv

and saw VIRTUALENVWRAPPER_SCRIPT ... pretty easy to figure out from there

A: To be able to execute the virtualenvwrapper functions, we need to first source the virtualenvwrapper.sh file. To find the location of that file, in a terminal execute:
which virtualenvwrapper.sh

If that doesn't produce any output, use find to find it.
find /usr/ -name "virtualenvwrapper.sh"

For me, the location was /usr/local/bin/virtualenvwrapper.sh
When PHP does system calls, it uses sh:
<?php
system('echo $0'); // echoes 'sh'

However the virtualenvwrapper.sh script fails when being executed with sh, so we need to use bash instead.
Another thing to note is that PHP system calls are separate subshells from each other, so if you do:
<?php
system('FOO=BAR');
system('echo $FOO');

This prints out an empty line. Where as the following prints BAR:
<?php
system('FOO=BAR && echo $FOO');

Therefore, we need to:

*

*Use bash instead of sh

*Source the virtualenvwrapper.sh

*Execute workon to change working virtual environments

*Execute any other commands needed

*Do all this in one single line

This is what I came up with and appears to be working correctly:
<?php
$commands = [
    'source /usr/local/bin/virtualenvwrapper.sh',
    'workon pootle',
    'pootle update_stores --project=AIWeb',
];

system('/bin/bash -c "'.implode(' && ', $commands) .'"');


text:
Q: React Hooks - Remove Specific Item from an array using Index I have two arrays,
const [imagesUrlArray, setURls] = useState([])

  const [imagesArray, setImages] = useState([])

using handle change below; imagesUrlArray is used to display the images on the screen, and imagesArray is saved to later update those same images to the database
const handleChange = (e) => {
    let selected = e.target.files[0]
        var selectedImageSrc = URL.createObjectURL(selected);
        addUrl(selectedImageSrc)
        addImage(selected)
    };

Though I now want to click the X(delete) button and remove the item at index of imagesUrlArray and imagesArray (say if the user no longer wants to use that image)

{ imagesUrlArray && imagesUrlArray.map((url,index) => {

  return (

       {/* × */}
       <button onClick={ () => handleRemove(index)} className="close">X</button>

)
   }
)}

I have tried splice and slice etc but still cannot find a perfect solution,
here is the handleRemove Function
const handleRemove = (index) => {

  const newImagesArray = imagesArray.splice(index);

  const newImagesUrlArray = imagesUrlArray.splice(index);

  setImages(newImagesArray);

  setURls(newImagesUrlArray);
}

A: You can do something like this:
const handleRemove = (index) => {

  setImages(imagesArray.filter((x,i) => i !== index));

  setURls(imagesUrlArray.filter((x,i) => i !== index));

}

So, basically the idea is to skip the element at specific index and return the remaining items and set the state.


text:
Q: How to set azure automation scheduler time zone Now my website is on windows azure. I make a store procedure in database, then I execute it to update database every night on 0:00:00. I use azure automation to achieve this goal. So I write a Runbook which execute this store procedure. And add a scheduler to this task. Now this all work well, but in the scheduler, I set the time "0:00:00" which can't set the time zone.
(I am in China, but this task always run before 0:00:00 compared to my local time)
How can I specify the time zone when setting a scheduler on azure automation?

A: As you may already know that everything in Azure runs in UTC. If you want to run your task at midnight China time, what you could do is calculate the time difference (which I believe is 8:00 hours) and run your task at that time which would be at 4:00 PM UTC ( assuming my math is right).


text:
Q: What is the correct way to selectively publish in Meteor based on information in the database? For instance, when your permissions are group-based, and your user document has a list of groups that the user belongs to. I'm publishing docs in an Items collection, and you should only be able to view items with a groupOwner field matching a group you belong to.
It would be nice if you could autorun inside a publish, but I doubt you can:
Meteor.publish 'screened-items', ->
  Deps.autorun ->
    user = Users.findOne @userId
    return Items.find {groupOwner: {$in: user.groups}}

If you can't, this is the best I can come up with, but it's going to be slow and memory-intensive. Is this the only way to do it?
Meteor.publish 'screened-items', ->
  user = Users.findOne @userId

  # (hope that the db doesn't change between this line and the observeChanges)
  saved_items = Items.find({groupOwner: {$in: user.groups}}).fetch()
  # call @added on each item

  handle = Users.findOne(@userId).observeChanges {
    changed: (_, fields) =>
      if fields.groups
        new_items = Items.find({groupOwner: {$in: fields.groups}}).fetch()
        # compare new_items to saved_items, and call @added() or @removed() for each difference
  }

  @ready()
  @.onStop ->
    handle.stop()

A: You can achieve this two ways:

*

*Use the publish-with-relations package, for example:
Meteor.publish 'screend-items', ->
  # select the current user
  Meteor.publishWithRelations
    handle: this
    collection: Meteor.users
    filter:
      _id: @userId
    options:
      fields:
        groups: 1
    mappings: [
      key: 'groupOwner'  # and map to the `groupOwner` field on Items
      collection: Items
    ]

*Denormalize the relationship, providing a succinct list of users to use for publishing
Items._ensureIndex(userIds: 1) # best to index this field
# basic publications
Meteor.publish 'screend-items', ->
  # don't expose `userIds` to the client
  return Items.find({userIds: @userId}, {fields: userIds: false})

A: If you want the published docs to change when the userId changes, that is the default behaviour.

However, if the logged-in user changes, the publish function is rerun with the new value. - from docs.meteor.com.

Deps.autorun() only works on the client while Meteor.publish() only works on the server.  So you can not autorun inside of publish.
If you are okay to let the client see the 'groups' they're in, the code is a bit simpler because you can start and stop the subscription when the groups change.  Like this:
//on client
Deps.autorun( function() {
  Meteor.subscribe( 'items', Meteor.user().groups );
});

//on server
Meteor.publish( 'items', function( groups ){
  var self = this;
  var user = Meteor.users.findOne( {_id: self.userId});

  if ( ! (user && user.groups === groups) )
    return;

  return Items.find({groupOwner: {$in: groups}});
});

Otherwise you would need use two observers inside the publish function - one to watch user for changes to groups and another to manage publishing items that are in the group.  See this example of doing a join of collections that way.


text:
Q: Socket.io: Real time web app persistence trade offs I have a real time app that I have already built. After reading some documentation on googles real time api, or mozilla's togetherjs I'm questioning my currently architecture. Obviously their are trade off's in terms of persistence (which I need to restore state) and speed of the updates.  Here's the basic model I have now:
Client changes object -> client does a POST to server -> its persisted to Mongo -> Server broadcasts updated object via socket io to every client that cares
This guarantee's persistence but sometimes I feel its slows down the real time updates.  The model I'm considering:
Client changes object -> broadcast object change via socket io to all clients that care (hub/spoke model) -> then fires a POST to server -> store in Mongo
In this model the clients aren't waiting for the roundtrip to the database, which seems faster.  A third model I've considered:
Client changes object -> broadcast object change via socket io to all clients that care (hub/spoke model) -> server asynchronously stores in Mongo
I feel like its a tradeoff of speed and up to date persistence.  Just wanted to get someone else's take on it.


text:
Q: Element not recognized Working on Coded UI testing and for scripts developed using Record Capture and playback feature (ctrl +I).
The problem is when the page has sub-menus (e.g. I need to hover over menu link then click sub-menu). When I record and capture element using Ctrl+I and executed a script it recognizes, but when I ran the script for the second time the element gets changed and it's not recognized.
I have tried simple x path utility posted here but coudn't able to use this feature. What would be the problem for always element id's getting changed. How to resolve it ?

A: Are you sure it isn't a nested object?
See http://executeautomation.com/blog/how-to-identify-all-the-child-elements-within-a-page-in-coded-ui-test-cuit/
You could also try EnsureClickable()

A: There could few reasons behind not recognizing an element:

*

*List item Element is not visible when you are trying to click on it.

*If Type of Parent Element is e.g. winclient then it's difficult in coded UI to identify its child elements.

There could various solutions, you can try:

*

*First Click on Menu Item and then click on Sub Menu Item, if you are directly clicking on sub menu item in your recorded script, this will make sub menu element visible.

*Also you can check the visibility from Coded UI Test Builder-> Add Assertion button then going to UI Control Map, then select the element in tree and click on Refresh. It will show if element is visible or not.

*If Ids are changing, then you can various other properties like Name, ClassName, InnerText, ControlType, TagInstance, ControlName etc. whichever is supported by Element.


text:
Q: Securing a connection from iPhone to server I'm working on an iOS app, where it needs to connect to a web service that located on a web server. And it needs to give an arguments to some .php files that will receive these arguments via the POST method. The problem is that I don't want anyone to look/know these arguments, and what I've tried is that WireShark can discloses/sniffs the values of these arguments.
So, what is the suitable approach to secure the connection?, I thought about encrypting the data befor sending them to the server (using simle secrete/single key, since my data are not highly sensitive) and the same for fetching data from the server, if I'd go with this approach, then I'll need to implement my own classes, but I'm running out of time.
Thanks in advance :)

A: Https is an option here, but won't hide data from a determined attacker. An attacker can MITM himself to reverse engineer whatever protocol it is that you are using to communicate from iphone to server, and even modify requests in real time!
Here's a good example of how a researcher was able to reverse engineer's Apple's Game Center protocol and artificially set his own high score in an iOS app:
http://corte.si/posts/code/mitmproxy/tute-gamecenter/index.html
If you are concerned about this type of attack, then you should encrypt your payload using a pre-shared key and a symmetric cipher like AES-256 or blowfish.

A: Use https instead.  Your data are not highly sensitive, so this should be enough.  You may not even have to change your iPhone code (other than the URL change), although this depends on your server's certificate.


text:
Q: Macos Mojave restart got stuck I was trying to update my Mac to Mojave but when it was restarting it got stuck and all I see is apple logo. I am not sure what happened and how can I get back to start m Mac. Any help please.
This is what I see in photo below.

A: I assume that you didn't shut the lid down while updating it or basically didn't put it to sleep through anyway.
if you didn't, I just recommend waiting.
if still stuck, try reinstalling using recovery mode. which is holding CMD-R just after power up during restart . Apple support for reference


text:
Q: edit the etc\hosts file Using C or a bat file, I'm trying to edit the file hosts file from c:\Windows\System32\drivers\etc but I can;t bc it is write protected.
Can you tell me what can i do?

A: The program modifying the host file needs to run as Administrator

A:
Can you tell me what can i do?

Yes. Get the Administrator password or find another way to solve your problem.
If you describe what is your problem (rather than your issue on a possible solution) maybe we can figure a different (working) solution.

A: Open the file from VS code. VS code it self will show a dialog box. Confirm it.


text:
Q: Typescript generic object in array only match the specified Records Demo: https://tsplay.dev/Nnavaw
So I have an array with the following definition:
Array<{
      id?: string;
      text?: string;
      date?: Date;
    }>

That interfers with the following implementation:
data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>

How can I tell Typescript that the Array can also include other properties other than Partial<Record<K, string>> & Partial<Record<H, string | number | null>>?
Because if I'll pass an array with the following defintion it gives me this error:
Type 'Date' is not assignable to type 'string | number | null | undefined'.

Complete function:
ifAlreadyExistsString<K extends PropertyKey, H extends PropertyKey>(
    data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>,
    key: K,
    value: string,
    idKey?: H,
    idValue?: string | number | null
  ): boolean {
    return (
      data.filter((item) => {
        // If the value is found in the data array
        if (item[key] && item[key]?.trim().toLowerCase() === value.trim().toLowerCase()) {
          // Then check if the id of the value matches the found entry
          // If the ids are matching, then you are currently editing this exact entry
          // If the ids are NOT matching, then you have found a duplicate.
          if (idKey && item[idKey] && idValue) {
            return !(item[idKey] === idValue);
          } else {
            // If no idKey is provided, then we have found a duplicate.
            return true;
          }
        }

        return false;
      }).length !== 0
    );
  }

A: If you don't pass in an idKey parameter, then the compiler can't use it to infer H.  What you'd like to happen here is that H should fall back to never, because  Record<never, string | number | null> is just {}, and you don't want to constrain the element type of data.  Unfortunately what actually happens is that the compiler uses the data array type to infer H.  It guesses that H should be  keyof (typeof data)[number], and then complains about it.  Oh well.
You need to step in and prevent H from being inferred as anything but possibly never when idKey is not passed.

One way to do this to overload the method so that there is one call signature for idKey being present and another for it being absent.  That looks like:
// call signature without idKey
ifAlreadyExistsString<K extends PropertyKey>(
  data: Array<Partial<Record<K, string>>>,
  key: K,
  value: string,
): boolean;

// call signature with idKey
ifAlreadyExistsString<K extends PropertyKey, H extends PropertyKey>(
  data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>,
  key: K,
  value: string,
  idKey?: H,
  idValue?: string | number | null
): boolean;

// implementation
ifAlreadyExistsString<K extends PropertyKey, H extends PropertyKey>(
  data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>,
  key: K,
  value: string,
  idKey?: H,
  idValue?: string | number | null
): boolean { /* snip impl */ }

You'll find that this now works:
console.log(this.ifAlreadyExistsString(data, 'text', 'no text')); // okay
/* AppComponent.ifAlreadyExistsString<"text">(
    data: Partial<Record<"text", string>>[], key: "text", value: string
  ): boolean (+1 overload) */

Another thing you could do is try to tell the compiler not to infer H from data, and to default to never.  You want to say that the H in the type of data is a non-inferential type parameter usage.  There's a feature request at microsoft/TypeScript#14829 for a syntax to do this.  The idea is that NoInfer<H> would evaluate to exactly H, but would not be usable for inference.
The feature request is still open.  However, there are some ways to emulate NoInfer<T> with current TypeScript features, which work in at least some circumstances.  One way is:
type NoInfer<T> = [T][T extends any ? 0 : never];

You can see that no matter what T is, NoInfer<T> will eventually evaluate to T.  But the compiler defers evaluation of T extends any ? 0 : never for generic T, and this will block inference:
ifAlreadyExistsString<K extends PropertyKey, H extends PropertyKey = never>(
  data: Array<Partial<Record<K, string>> & Partial<Record<NoInfer<H>, string | number | null>>>,
  key: K,
  value: string,
  idKey?: H,
  idValue?: string | number | null
): boolean { /* snip impl */ }

And now this works again:
console.log(this.ifAlreadyExistsString(data, 'text', 'no text'));
/* AppComponent.ifAlreadyExistsString<"text", never>(
     data: (Partial<Record<"text", string>> & Partial<Record<never, string | number | null>>)[],
     key: "text", value: string, idKey?: undefined,
     idValue?: string | number | null | undefined): boolean */

Playground link to code


text:
Q: How to tune EGit for large repositories? The problem:
I find EGit great and use it intensively, but it can be incredibly slow. It can get frustrating when it takes several minutes to complete operations that the C version of git (Cgit) does in less than a couple of seconds.
All operations are significantly slower than Cgit. For example switching branches will take 10's of seconds compared to near instant. A rebase can take several minutes compared to less than a couple of seconds.
Some details:
History size: 10114 commits  as reported with: git rev-list HEAD --count
Current Working directory size: 63.7 MB
Current .git size: 77.4 MB
Largest file size: 4.0 MB
OS: Linux - CentOS 5.5
File System: ext3
JVM: Oracle - Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
EGit and JGit version: 3.0.0.201306101825-r
I was previously running 2.3 but did not notice any change in performance after upgrading.
Could suitable window cache settings help:
I found the following quote in JGit's bugzilla here:

...EGit had to expose UI to allow users to configure it when working on
  bigger repositories.

Which sounds like it fits my case. So I looked around in eclipse and under Window -> Preferences -> Team -> Git found these Git Window Cache settings:

But how do I use them?
What do the different controls actually do? Has anyone had any success in getting EGit to be more responsive by using them?

A: Recommendations
As Matthias Sohn suggested, the Window cache limit appears to be most significant of these parameters.
For me, increasing this from "10 m" to "500 m" made a huge difference to how responsive egit was.
Details of each parameter
From the source code† of WindowCacheConfig.java:
Windows Size

packedGitWindowSize: size in bytes of a single window mapped or read in from the pack file

Default: 8 k
Window cache limit

packedGitLimit: maximum number bytes of heap memory to dedicate to caching pack file data.

Default: 10 m
Delta base cache limit

deltaBaseCacheLimit: maximum number of bytes to cache in delta base cache for inflated, recently accessed objects, without delta chains.

Default: 10 m
Stream File Threshold

streamFileThreshold: the size threshold beyond which objects must be streamed.
Objects smaller than this size can be obtained as a contiguous byte array, while objects bigger than this size require using anObjectStream.

Default: 50 m
Use virtual memory mapping

packedGitMMAP: true enables use of Java NIO virtual memory mapping for windows; false reads entire window into a byte[] with standard read calls.

Default: Unchecked
Not presented on the preferences page

packedGitOpenFiles: maximum number of streams to open at a time. Open packs count against the process limits.

Default: 128

† Thanks Jens Theeß for their comment on Matthias Sohn's answer containing a pointer to the source code.

A: *

*increase the window cache limit to a larger value, it's defining the size of jgit's cache used to map pack files into memory

*do you run gc (either from egit or native git) on your repository ? JGit/EGit don't run it automatically (yet). YOu may check the number of loose object in EGit's repositories view (click "Properties" and select tab "Statistics")

*how many commits does your repository have (age in year doesn't say anything since it could have an age of 10 years with 2 commits or 2 mio commits)

*which OS / filesystem are you using ?

A: EGit 3.5.0 will bring huge performance fix for large repositories - without "tuning" anything. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=440722
You can use nightly EGit build update site to get the fix immediately:
http://download.eclipse.org/egit/updates-nightly


text:
Q: Rails: Capitalize characters after certain string Using: Rails 3.0.3.
I have a string that could be seen as this one:

hello, how are you? oh, that's nice! i am glad you are fine. i am too.
i am glad to have met you.

I want each character following any of

 ! ? . to be capitalized. Basically make the string above look good.
Is there a standard functionality for that? What should I do?
ps. Tried to bold the characters in question, but it didn't work...

A: Using Nokogiri you can have any markup around the text, and it breaks on the
 etc.
ng = Nokogiri::HTML.fragment("
hello, how are you? oh, that's nice! i am glad you are fine. i am too.
i am glad to have met you.
")
ng.traverse{|n| (n.content = n.content.gsub(/(.*?)([\.|\!|\?])/) { " #{$1.strip.capitalize}#{$2}" }.strip) if n.text?}
ng.to_s

gives :
"
Hello, how are you? Oh, that's nice! I am glad you are fine. I am too.
I am glad to have met you.
"

I used strip twice, first because a sentence after stop/question/exclamation will have white space and not capitalize otherwise, then to put the spacing back I added a space before each sentence - the second strip removes the generated space at the start of the final output.

A: Going off Niklaos answer, I've improved it slightly to take into account the period and keeping spacing intact in the rendered HTML.
str.gsub(/(\
|\
|[?!.])([\s]*)([[:alpha:]]{1})/) {"#{$1}#{$2}#{$3.capitalize}"}

Edit: Added punctuation characters to be in a single character class, captured all in between whitespace to preserve spacing.  Much cleaner.

A: capitalize is the method you are looking for. although you have to do it for each sentence. You can easily parse that with nokogiri if you have to though

A: Hum I feel like it's time to call super Regex :)
str.gsub(/(\
|\
|! |\? )(.{1})/) {"#{$1}#{$2.capitalize}"}

That should to the job.
Note: this can be improved to have more flexibility.


text:
Q: Calling back history in bash I am a huge fan of this magic in my .inputrc which allow me to quickly autocomplete a command with the up arrow key.
"\e[A": history-search-backward
"\e[B": history-search-forward
"\eOA": history-search-backward
"\eOB": history-search-forward

However very often, I have to ssh on a vanilla linux where I have to use CTRL+R. I then usually became very unproductive because I don't know how to use this command.
It is time to question my workflow. Can I be more productive by using the native bash history reverse search than my .inputrc magic?
Concrete use case
I would like to recall the last python line I have written. With my solution I do pyt+ ↑ + Enter
With the reverse-i-search, if I do CTRL + R, pyt. I usually get any command containing pyt, not the last command starting with python.
More annoying, I usually realize I should use my history when I already typed let's say pyth. If I hit CTRL + R I get:
(reverse-i-search)`': pyth

Which is very confusing because if I type o I suddenly get a WTF command I typed ages ago containing just a o.
I am totally sure I am not using the reverse-i-search the right way. What am I missing?

A: Are you using additional CTRL + R keystrokes to go beyond the first match?
In your example above, when you hit pyth you can then continue matching further back with additional CTRL + R presses.
Is that what you were looking for?

Update: Added example below, as requested.
Example:  I want to match the older of these two similar commands.
$ python -m this
# ... snip...

$ python -c "import this"
# ... snip...

Now when you:

*

*CTRL + R

*Start typing pyt
At this point you have matched the latter of the two commands.  Not the one you want (in this example).

*Hit CTRL + R one more time

At this point you will be matching the command you desire.


text:
Q: Creating a reusable class in python I need to work with remote files transparently as if they were local files in some python code I'm writing, so I decided to use SFTP for this task.  The following code example works (it prints the first line of the remote file):
import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='192.168.8.103', username='root', password='pyjamas')
sftp = client.open_sftp()
test = sftp.open('/var/log/example/ingest.log', mode='r', bufsize=1)
print test.readline()

I am going to be connecting to many files, so I decided to write a class that gives me an SFTPFile object.  Examine the following code:
import paramiko

class RemoteLog(object):
    """This class implements the remote log buffer."""

    def __init__(self, host, user='', pw='', log=''):
        """Initializes a connection to a remote log."""

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, username=user, password=pw)
        sftp = client.open_sftp()
        self.log = sftp.open(log, mode='r', bufsize=1)

if __name__ == "__main__":
    test = RemoteLog(host='192.168.8.103', user='root', pw='pyjamas', log='/var/log/example/ingest.log')
    print test.log.readline()

Unfortunately readline() in this scenario returns nothing.  There are no errors or obvious explanations.
How should I replicate the functionality from my first code snippet into a reusable class?

A: It appears that the sftp connection is closed when the variables go out of scope in __init__.  Storing a reference to those in the class fixes the problem.
def __init__(self, host, user='', pw='', log=''):
    """Initializes a connection to a remote log."""

    self.client = paramiko.SSHClient()
    self.client.load_system_host_keys()
    self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.client.connect(hostname=host, username=user, password=pw)
    self.sftp = self.client.open_sftp()
    self.log = self.sftp.open(log, mode='r', bufsize=1)

As an extra piece of advice, you might consider implementing the standard file object functions and hide the self.log reference behind your object.  Instead of test.log.readline(), you really should be able to use test.readline() as you are trying to wrap a file-like object (you should really implement a close() method as well).  There's a bit of work doing so, but it's a one-time effort and will make the code that uses this class a lot cleaner.


text:
Q: How to print data.frame values line by line I want to convert data.frame to this format:
(col1row1Value, col2row1Value, ... colNrow1Value),
(col1row2Value, col2row2Value, ... colNrow2Value),
...
(col1rowNValue, col2rowNValue, ... colNrowNValue)

this is my dirty solution:
convert <- function(df) {
  df <- data.frame(lapply(df, as.character), stringsAsFactors = F)

  result <- ""
  for(i in 1:nrow(df)) {
    x <- paste(df[i, ], collapse = ", ")
    result <- paste0(result, "(", x, "),\n" )
  }
  result <- substr(result, 1, nchar(result) - 1)
  result
}

test:
cat(convert(iris[1:5,]))

any ideas how to imporove it?

A: Does this help?
iris$new<- apply(iris, 1,paste0, collapse = ",")
print(apply(iris[,6, drop= F], 2, function(f) paste0("(", f, ")", collapse= ",")))

A: Perhaps with the tidyverse :
convert <- function (df)
  df %>% mutate_if(Negate(is.character),as.character) %>%
    mutate(id=row_number()) %>%
    gather(k,v,-id) %>%
    group_by(id) %>% summarise(z=paste0("(",paste(v,collapse=", "),")")) %>%
    pull(z) %>% paste(collapse=",\n")

cat(convert(iris[1:5,]))
#(5.1, 3.5, 1.4, 0.2, setosa),
#(4.9, 3, 1.4, 0.2, setosa),
#(4.7, 3.2, 1.3, 0.2, setosa),
#(4.6, 3.1, 1.5, 0.2, setosa),
#(5, 3.6, 1.4, 0.2, setosa)

A: Here's another way to do it (you can wrap this in a function if you want).
itest <- iris[1:5,] %>%
  mutate(Species = as.character(Species))

ct <- 1:nrow(itest)

tbl <- tibble()

for (i in ct) {

  r <- itest[i,]
  newct <- 1:ncol(r)

  vals <- character()

  for (i in newct) {

    new_val <- r[,i]

    vals <- c(vals,new_val)
  }

  new_tbl <- tibble(stringrow = paste(vals,collapse=', '))

  tbl <- bind_rows(tbl,new_tbl)

}

Results:
# A tibble: 5 x 1
  stringrow
  <chr>
1 5.1, 3.5, 1.4, 0.2, setosa
2 4.9, 3, 1.4, 0.2, setosa
3 4.7, 3.2, 1.3, 0.2, setosa
4 4.6, 3.1, 1.5, 0.2, setosa
5 5, 3.6, 1.4, 0.2, setosa


text:
Q: Имитация нажатия Ctrl+A, Ctrl+X, Ctrl+V Python Необходимо сделать имитацию нажатия клавиш Ctrl+A, Ctrl+X и Ctrl+V. Пробовал сделать вот так:
import win32com.client

shell = win32com.client.Dispatch('WScript.Shell')
shell.SendKeys('^A')
shell.SendKeys('^X')
# Кое-какие действия с буфером обмена
shell.SendKeys('^V')

Не получается. Причём, комбинации типа '+%', 'A' и т.д. работают прекрасно. Буду премного благодарен за название модуля, от которого стоит отталкиваться.
Windows 10/Python 3.6.1

A: Разобрался. Прописывая shell.SendKeys('^A') необходимо использовать НИЖНИЙ РЕГИСТР. То есть: shell.SendKeys('^a'). Тогда сработает.


text:
Q: Moving through allocated bytes I have following declaration data:
temp db 50 DUP(0)

How do I access each byte?
Let's say I do mov temp, 48 and then want to move 49 into the next byte of the allocated ones. I tried to
inc temp
mov temp, 49

but it just increased temp value to 49

A: E.g.
mov [temp + 1], 49

or, if you want to dynamically select the slot in temp to store a value in
mov [temp + ebx], 49

where ebx holds the index value (could be any register)


text:
Q: In ext.net, how do I align a tabpanel button to the right? I would like to align the button of the right, but keep the content tabs on the left. This is my code:
<ext:TabPanel ID="TabPanel1" runat="server" Height="295" Plain="true" DeferredRender="false" meta:resourcekey="TabPanel1Resource1">
       <TabBar>
          <ext:Button runat="server" Icon="ArrowOut" meta:resourcekey="fullscreenResource1">
             <DirectEvents>
                  <Click OnEvent="edit_fullOpenAdd" />
             </DirectEvents>
          </ext:Button>
        </TabBar>
        <Defaults>
           <ext:Parameter Name="autoScroll" Value="true" Mode="Raw" />
        </Defaults>
           <Items>
               ......the content ......
           </Items>
</ext:TabPanel>

Any Ideas?
Thank you!
Edit: I was told to try tabCls: 'right-tab', but I do not know how to implement this.

A: Use TabStrip control.
Please see this example: http://examples.ext.net/#/TabPanel/TabStrip/Overview/


text:
Q: How to solve error with YAML, Preamble (LaTex) and Pandoc conversion I started using markdown together with pandoc a few weeks ago. I'm especially fond of the markdown editor writemonkey v.3! I have one slight problem with converting my .md to .pdf, and I it's caused by the first line in my document. The first line in the document (see below) is how you give the document a name in writemonkey.
name: seminarium 1

---
author: my name
date: 22 Augusti 2020
bibliography: testlibrary.bib
geometry:
- top=2.5cm
- bottom=2.5cm
- left=2.5cm
- right=2.5cm
pagesize: a4
font: Times New Roman
fontsize: 12pt
header-includes:
   - \usepackage{setspace}
   - \setstretch{1.0}
   - \pagenumbering{gobble}

---

If I remove this first line, the pandoc conversion works like a charm. Otherwise I get this:
pandoc  sem1.md -o sem1.pdf --bibliography library.bib -V lang=sv
Error producing PDF.
! LaTeX Error: Can be used only in preamble.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.78 \usepackage

Now - I realize that I've combined a YAML with LaTex code, I am hoping that my formatting is "bad" and that I might improve it so I don't have to remove the first line every time. Maybe tell Pandoc/LaTex to ignore the first line or make a separate .yaml file would help?

A: Ok! This what I did. Works great with Writemonkey. Just copy-paste in Notepad and save as a .ps1 file and run in Powershell!
CD C:\Users\username\Desktop\ppp2020 # Filepath of .md, .yaml and .bib

Get-Content cap.md -Encoding UTF8 | Select-Object -Skip 2 | Set-Content cap_temp.md -Encoding UTF8 # Removes the first line (name:) from markdown document

pandoc  cap_temp.md default.yaml  -o cap.pdf --bibliography library.bib -V lang=sv # converts .md to .pdf

Remove-Item 'C:\Users\username\Desktop\ppp2020\cap_temp.md' # This removes the tempfile


text:
Q: PHP preg_replace_callback is there a way to break the search? Is there a way to break the search for preg_replace_callback when it reaches a certain index?
For example:
            $content = preg_replace_callback('/'.preg_quote($_POST['query'],'#').'/i', function($matches) use($replacements,&$index) {
                if ( $index > count($replacements) ) {
                    // I tried break; but doesn't work
                }

                if ( $replacements[$index] != '' ) {
                    $matches[0] = $replacements[$index];
                }
                $index++;
                return $matches[0];
            }, $content);

A: You can just use the elseif to ignore the second if
       $content = preg_replace_callback('/'.preg_quote($_POST['query'],'#').'/i', function($matches) use($replacements,&$index) {
            if ( $index > count($replacements) ) {
                // I tried break; but doesn't work
            } elseif ( $replacements[$index] != '' ) {
                $matches[0] = $replacements[$index];
            }
            $index++;
            return $matches[0];
        }, $content);

edit
preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit [, int &count]] )

limit
The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
count
If specified, this variable will be filled with the number of replacements done.


text:
Q: How to set OnSeekBarChangedListener for SeekBar used in AlertDialog via LayoutInflater I am trying to access a SeekBar in a AlertDialog.
I need to either setOnSeekBarChangeListener(), or access the SeekBar.getProgress() to get its value. Where do I do this? Is it possible?
The dialog is shown using showDialog(id) from onOptionsItemSelected.
The following code is used in onCreateDialog to create the AlertDialog with custom content which includes a SeekBar.
case CALIBRATE_DIALOG_ID: {
            // This example shows how to add a custom layout to an AlertDialog
            LayoutInflater factory = LayoutInflater.from(this);
            final View calibrateView = factory.inflate(R.layout.dlg_calibrate, null);
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle("Calibrate")
                .setView(calibrateView)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //mSeekBar1 = (SeekBar) findViewById(R.id.SeekBar01);
                        //Toast.makeText(ctx, mSeekBar1.getProgress(), Toast.LENGTH_SHORT);

                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
        }

I can't do it in the main activity onCreate; the SeekBar has not been created yet. I thought I would be able to get a handle on the SeekBar.getProgress() value in the Ok Button's onClick handler but could not.
Any suggestions would be great!
thanks
patrick

A: You can get your SeekBar by calling findViewById() on your calibrateView, presumably.


text:
Q: How to Get County Information for the given address when we use Rest API I am using below code to get the address information and i am getting entire address. But i only need county for the given city and zip of USA. Please help
function getCounty()
{

    $.ajax({
  url: 'https://geocoder.api.here.com/6.2/geocode.json',
  type: 'GET',
  dataType: 'jsonp',
  jsonp: 'jsoncallback',
  data: {
    city: 'Farmington',
    postalcode: '48335',
    country: 'usa',

    app_id: '**************************',
    app_code: '************************',
    gen: '9'
  },
  success: function (data) {
alert(JSON.stringify(data));

  }
});

}

A: Please try below code to access County attribute of the response.
Hope this help.
alert(data.Response.View[0].Result[0].Location.Address.County);

And please check below full JSON response for the request.
{
  "Response": {
    "MetaInfo": {
      "Timestamp": "2019-01-09T07:08:18.912+0000"
    },
    "View": [
      {
        "_type": "SearchResultsViewType",
        "ViewId": 0,
        "Result": [
          {
            "Relevance": 1,
            "MatchLevel": "postalCode",
            "MatchQuality": {
              "City": 1,
              "PostalCode": 1
            },
            "Location": {
              "LocationId": "NT_9usvaftBv-o9T6WyVpnWRC",
              "LocationType": "area",
              "DisplayPosition": {
                "Latitude": 42.47427,
                "Longitude": -83.40889
              },
              "NavigationPosition": [
                {
                  "Latitude": 42.47427,
                  "Longitude": -83.40889
                }
              ],
              "MapView": {
                "TopLeft": {
                  "Latitude": 42.48732,
                  "Longitude": -83.4355
                },
                "BottomRight": {
                  "Latitude": 42.43954,
                  "Longitude": -83.37537
                }
              },
              "Address": {
                "Label": "48335, Farmington, MI, United States",
                "Country": "USA",
                "State": "MI",
                "County": "Oakland",
                "City": "Farmington",
                "PostalCode": "48335",
                "AdditionalData": [
                  {
                    "value": "United States",
                    "key": "CountryName"
                  },
                  {
                    "value": "Michigan",
                    "key": "StateName"
                  },
                  {
                    "value": "Oakland",
                    "key": "CountyName"
                  },
                  {
                    "value": "N",
                    "key": "PostalCodeType"
                  }
                ]
              }
            }
          }
        ]
      }
    ]
  }
}


text:
Q: ODE with Laplace transform: the jump of $\dot y$ I solved this eq. using the Laplace Transform:
$\ddot y+4\dot y+13 y=\delta(t-2\pi)-\delta(t-7\pi)$
The sol. is:
$y(t)=\frac{1}{3} e^{2 t} (-e^{14 \pi} \theta(t-7\pi) sin(3 t)+e^{4 \pi} \theta(t-2 \pi) sin(3 t)+2 sin(3 t)+3 cos(3 t))$
or
$y(t)=\begin{cases}
  e^{-2t}\cos {3t}+\frac{2}{3}e^{-2t}\sin{3t} \quad \mbox{if} \quad t<2\pi\\
  e^{-2t}\cos {3t}+(\frac{2}{3}+\frac{1}{3}e^{4\pi})e^{-2t}\sin{3t}\quad \mbox{if} \quad2\pi<t<7\pi \\
  e^{-2t}\cos {3t}+(\frac{2}{3}+\frac{1}{3}e^{4\pi}+\frac{1}{3}e^{14\pi})e^{-2t}\sin{3t}\quad \mbox{if} \quad t>7\pi
 \end{cases}$
Now I am being asked what is the "jump" in $\dot y(t)$ at $t=2\pi$ and $t=7\pi$.
Could any one explain me a way to answer it?
I know how to find the difference in $\dot y$ at a certain point but not by what extent.

A: They're asking for
$$\lim_{t \to 2 \pi^+} y'(t) - \lim_{t \to 2 \pi^-} y'(t)$$
and the same at $7 \pi$. However, you don't need the solution to calculate these, all you need to assume is that $y(t)$ and $y'(t)$ are bounded (or even just integrable). Rewrite the equation
$$y''(t) = -4y'(t) - 13y(t) + \delta(t-2\pi)-\delta(t-7\pi)$$
and integrate both sides around $2 \pi$:
$$\int_{2 \pi - c}^{2 \pi + c} y''(t) dt = \int_{2 \pi - c}^{2 \pi + c} -4y'(t) - 13y(t) + \delta(t-2\pi)-\delta(t-7\pi) dt$$
By the FTC, the left hand side is $y'(2 \pi+c)-y'(2 \pi-c)$, so the jump at $2 \pi$ will be the limit as $c \to 0$ of the right hand side. In other words
$$\lim_{c \to 0} y'(2 \pi + c)-y'(2 \pi - c) = \lim_{c \to 0} \int_{2 \pi - c}^{2 \pi + c} -4y'(t) - 13y(t) + \delta(t-2 \pi) - \delta(t - 7 \pi) dt$$
Using that $y'$ and $y$ are integrable along with properties of the delta function we get
$$\lim_{c \to 0} y'(2 \pi + c)-y'(2 \pi - c) = 0 + 0 + 1 + 0 = 1.$$
By looking at the term that survived, you can see the pattern: if the equation is linear, its order is $n$, and the right side contains $a \delta(t-b)$, then the $(n-1)$th derivative of the solution will have a jump of size $a$ at $b$.


text:
Q: JQuery Flickering On Scroll I'm trying to change a fixed footer element to relative when it hits a certain scroll depth using jQuery. The code works but there is a noticeable flicker effect as it changes from relative to fixed because the class keeps being added/removed.
Should there be a delay/wait between the switch? Or something else to stop the flicker?

$(window).scroll(function() {
  var distanceFromBottom = Math.floor($(document).height() - $(document).scrollTop() - $(window).height());

  if (distanceFromBottom < 260) {
    $(".js-subscribe-bar").addClass("fixed");
  } else {
    $(".js-subscribe-bar").removeClass("fixed");
  }
});
.subscription-wrapper {
  position: fixed;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 80;
}

.fixed {
  position: relative;
}

@media (min-width: 1390px) {
  .subscription-wrapper {
    bottom: auto;
    left: auto;
    top: 227px;
    position: fixed!important
  }
}

@media (max-width: 1389px) {
  .ribbon--subscription {
    margin: 0
  }
}

.ribbon--subscription {
  height: 35px;
  text-transform: none;
  padding: 0 16px;
  width: 100%
}

.ribbon--subscription:after,
.ribbon--subscription:before {
  left: -30px
}

.ribbon--subscription:before {
  border-width: 0 30px 40px 0
}

.ribbon--subscription:after {
  border-width: 0 0 40px 30px
}

@media (min-width: 1390px) {
  .ribbon--subscription {
    height: 70px
  }
}

Some text

A: Did you forget to insert return false at the end of scroll function
return false;