Iterating over keys and values of a dictionary in mustache / pystache

Question: Suppose I have simple dictionary like this:
d = {'k1':'v1', 'key2':'val2'}

How can I render key, value lines in pystache using that dictionary?
Answer: You have to transform your dictionary a bit. Using the mustache syntax, you can only iterate through lists of dictionaries, so your dictionary d has to become a list where each key-value pair in d is a dictionary with the key and value as two separate items, something like this:
>>> [{"k": k, "v": v} for k,v in d.items()]
[{'k': 'key2', 'v': 'val2'}, {'k': 'k1', 'v': 'v1'}]

Complete sample program:
import pystache

tpl = """\
{{#x}}
 - {{k}}: {{v}}
{{/x}}"""

d = {'k1':'v1', 'key2':'val2'}

d2 = [{"k": k, "v": v} for k,v in d.items()]
pystache.render(tpl, {"x": d2})

Output:
 - key2: val2
 - k1: v1

Answer: You could also use tuples, a bit less verbose:
import chevron

tpl = """\
{{#x}}
 - {{0}}: {{1}}
{{/x}}"""

d = {'k1':'v1', 'key2':'val2'}

d2 = [(k, v) for k,v in d.items()]
print(chevron.render(tpl, {"x": d2}))


Resize Modal Window in Javascript

Question: I'm trying to resize my modal dialog window when certain items are hidden/shown.
window.resizeTo(800, 600);

I've tried using code like above, but it doesn't seem to work.  I think because it is a modal dialog, and not a regular window.  Any suggestions as to how I could resize this?
Comment: Edited: This is not a duplicate of a resize jQuery modal question.  The above question and tags do not list jQuery as being an item in use.
Comment: correct, jQuery is not in use.
Answer: If you're trying to resize the modal dialog window from within the window itself, you might be tempted to use the javascript window.resizeTo() or window.resizeBy().
However, those will not work.  Instead, use:
window.dialogWidth='640px';
window.dialogHeight='480px';

P.S.
Rsolberg: The poster did say modal dialog window.  That seems like the way I'd describe it. I'm not sure that could be interpreted as being related to jQuery.  I'd remove the jQuery answer in order to avoid confusion.
Answer: You'll want to identify the element or container ID and do something like this:
document.getElementById('MyModal').style.height = '500px';
document.getElementById('MyModal').style.width = '800px';

If you are using jQuery for this it can be quite a bit easier as you can attach it to the actual show modal function.
Edit
Within the javascript functions above, MyModal will be the ID of the container or modal.  For example, if you are using a DIV for the outer element of your modal, you would set the DIV up like this:

CONTENTS OF MODEL

EDIT #2
Since this is not a "modal" as most would describe today, its more of a new window popup, this line of code should work for you (found it here):
window.open('http://www.pageresource.com/jscript/jex5.htm','mywindow','width=400,height=200')

Comment: This looks like exactly what I need.  However, where on the page would 'MyModal' be set?
Comment: Thanks R, but I think that maybe I'm not describing my scenario completely.  I open the modal using showModalDialog, and it opens up a different aspx page in that dialog.  I've tried accessing it via Page Title and a couple other things, but that hasn't seemed to work.  Thanks for the help!
Comment: When you say "modal" is it a layer being added to the current webpage, or are you literally just opening a new webpage all together?  Is this like a popup window?
Comment: it is a pop-up.  A different page from the same website is brought up in a modal dialog to act as a form for editing values displayed in a gridview on the parent page.
Comment: I've added a bit more info.  Let me know if that helps at all.

Resize Modal Window in Javascript


Add php user input controller to wordpress customizer

Question: Trying to customize the Wordpress Theme Customizer to allow users to input either a shortcode or a custom php string. Currently, I have many user input fields for text input, but I can't figure out how to sanitize the text correctly to allow for php.
Any suggestions on where to start?
Answer: Thank you user5552351 for your response.
After looking at the codex you referenced in your comment, I realized I was way over thinking the solution.
Turns out all I needed was to give the user a text input that allows for basic brackets [] and apostrophes '' while inside a do_shortcode function.
<?php echo do_shortcode(get_theme_mod( 'THEME_MOD_ID', 'THEME_MOD_DEFAULT_VALUE' ));?>

where THEME_MOD_ID is the identifier for the Theme Customizer Control. So Basically there's a section in my theme customizer called 'Contact' that holds a text input setting/control called 'custom_contact_form', where a user can input a shortcode (ex: [simple_contact_form] ) and it will replace everything between do_shortcode( + ). So my code might look something like this:
<?php echo do_shortcode(get_theme_mod( 'custom_contact_form', '' ));?>


Async in 4.5: Cancellation and Timeout

Question: I have a long running process inside a HTTPHandler that I asynchronously perform using Async Await .net 4.5
This works perfectly as expected...
How can I add a timeout so that the string 'timeout' is returned if the process takes too long?
Protected Async Sub button1_Click(sender As Object, e As System.EventArgs)
    Dim asyncHandler = New AsyncHandler
    Await asyncHandler.ProcessRequestAsync(HttpContext.Current)
    Response.Write(asyncHandler.Result)
End Sub

Public Class AsyncHandler
    Inherits HttpTaskAsyncHandler

    Public Property Result As String

    Public Async Function ProcessRequestAsync(context As HttpContext) As Task
        Me.Result = Await DoLongRunningProcessAsync(context)
    End Function

    Private Function DoLongRunningProcessAsync(context As HttpContext) As Task(Of String)

        'TODO: add a timeout so that if this takes too long we return "timeout":

        Return Task.Run(Of String)(Function() DoLongRunningProcess(context))

    End Function

    Private Function DoLongRunningProcess(context As HttpContext) As String
        'perform long running process....

        Return "success"
    End Function

End Class

Answer: Here is what I finally implemented:
Created a CancellationToken with a timeout value x milliseconds
Added a try catch to catch the error: OperationCanceledException
Public Async Function ProcessRequestAsync(context As HttpContext) As Task
        Dim cts As CancellationTokenSource = New CancellationTokenSource(30000) 'eg: 30 seconds
        Try
            Me.ResultCode = Await DoLongRunningProcessAsync(HttpContext.Current, cts.Token)
        Catch ex As OperationCanceledException
            Me.ResultCode = "timeout"
        End Try
End Function

Pass the CancellationToken to the signature of DoLongRunningProcessAsync method
Detect a timeout by calling ThrowIfCancellationRequested
Private Function DoLongRunningProcessAsync(context As HttpContext, ct As CancellationToken) As Task(Of String)
        Return Await Task.Run(Of String)(
            Function()
                Dim resultCode As String = DoLongRunningProcess(context)

                'detect timeout:
                ct.ThrowIfCancellationRequested()

                Return resultCode
            End Function)
End Function

Here is a great article I found that really helps:
Async in 4.5: Enabling Progress and Cancellation in Async APIs
Answer: I do not knot VB.NET, but I usually do this in C# like in example below:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

// Make sure that we have a way to cancell long running
Task<SomeClass> longRunningTask = GetSomethingAsync(cancellationTokenSource.Token);

// One of the task should be finished
if (longRunningTask == await Task.WhenAny(longRunningTask, Task.Delay(30000)))
{
     // Long running task completed
     SomeClass result = await longRunningTask;
}
else
{
     // Task.Delay(30000) was finished
     cancellationTokenSource.Cancel();
}

Comment: `CancellationTokenSource` can take a time span as a constructor argument, which greatly simplifies this approach.
Comment: +1 to @StephenCleary - there's also the typical 'milliseconds as int' overload available as well - http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource.cancellationtokensource.aspx
Answer: Normally TPL code supporting timeout does so through CancellationToken(Source) as mentioned by @outcoldman and @StephenCleary.  However, in your scenario you said you wanted the timeout path to also return a string, just a different one.
Because of that, instead of using CancellationToken(Source), it will probably be simpler just to treat your timeout code as another task that produces a string and then pick whichever task (timeout task or 'real' task) finishes first and return that string.
I changed your DoLongRunningProcess (the innermost function) to be async and returning Task(Of String) just so you wouldn't have to Task.Run it.
The 'Await Await' might look odd, but Task.WhenAny returns a Task(Of Task(Of T)) so the first Await is to get to the particular Task that finished first, and then we Await that in order to get the actual string result.
Sub Main
    MainAsync().Wait()
End Sub

' Define other methods and classes here
Public Async Function MainAsync As Task
    Dim asyncHandler = New AsyncHandler
    Await asyncHandler.ProcessRequestAsync(System.Web.HttpContext.Current)
    Console.WriteLine(asyncHandler.Result)
End Function

Public Class AsyncHandler
    Inherits HttpTaskAsyncHandler

    Public Property Timeout As TimeSpan = TimeSpan.FromSeconds(10)

    Public Property Result As String

    Public Overrides Async Function ProcessRequestAsync(context As HttpContext) As Task
        Me.Result = Await DoLongRunningProcessAsync(context)
    End Function

    Private Async Function DoLongRunningProcessAsync(context As HttpContext) As Task(Of String)

        'TODO: add a timeout so that if this takes too long we return "timeout":

        Dim workerTask As Task(Of String) = DoLongRunningProcess(context)
        Dim cancelTask As Task(Of String) = DoTimeout()

        Return Await Await Task.WhenAny(workerTask, cancelTask)

    End Function

    Private Async Function DoTimeout() As Task(Of String)
        Await Task.Delay(Timeout)

        Return "timeout"
    End Function

    Private Async Function DoLongRunningProcess(context As HttpContext) As Task(Of String)
        'perform long running process....

        Await Task.Delay(TimeSpan.FromSeconds(15))

        Return "success"
    End Function

End Class

Comment: Great alternative approach - but should really be using cancellation tokens
Comment: Agree with @geo1701.  CancellationToken should be favored, as the above approach could actually end up crashing the web server in certain circumstances.

Async in 4.5: Cancellation and Timeout


external style sheets, specifying absolute or relative paths

Question: the href portion of the the link tag for including external stylesheets is confusing to me, especially since most folks don't use an entire URL.
For example, in
  <link rel="stylesheet" href="mystyles.css" type="text/css" media="screen">

if I wanted to put my stylesheet in a subdirectory off wwwroot, what would be the difference in attempting to reference it via:
a) href="/someDir/mystyles.css"
b) href="./someDir/mystyles.css"
c) href="someDir/mystyles.css"
Thanks Much
Comment: only option c would do anything. http://www.w3.org/TR/WD-html40-970917/htmlweb.html
Comment: option b and c are the same actually. "./" refers to the current directory.
Comment: yah, I forgot that, thanks.  But why do folks even use the "./" style.  Hmm.
Comment: I think some people are just used to it from working with *nix environments. I think it kinda looks more assuring that when you're referencing a file, it's from the current directory.
Comment: I think you're right Matt -- thanks for your comment.
Answer: This is basic relative URL syntax. There is nothing CSS specific about this.
Assuming this appears in http://example.com/foo/bar/index.html

href="/someDir/mystyles.css"

http://example.com/someDir/mystyles.css

href="./someDir/mystyles.css"

http://example.com/foo/bar/someDir/mystyles.css

href="someDir/mystyles.css"

http://example.com/foo/bar/someDir/mystyles.css
And you didn't mention href="../someDir/mystyles.css"
Which would be: http://example.com/foo/someDir/mystyles.css
Comment: Thanks, so b and c are identical it appears.  Thanks for providing a "D".  Do you have a preference on technique(s) to use?  Thanks.


setjmp and longjmp implementation

Question: basically my problem in short is my implementation for setjmp and longjmp
doesn't work. the reason why i'm asking in this form not in (code review) is that i'm new to assembly i've little background and still learning but still not sure about the code (please read until the end).
first i'v executed the code on two platforms with three different compilers
and that's the reason why i'm sure that i'm doing something wrong with the assembler.
platforms: mac OS 10.12.5 x86_64 , ubuntu linux x86
compilers: Apple LLVM clang 8.0.0 x86_x64 ,clang 3.9.1 x86_x64 ,gcc 6.3 x86
i've compiled the code in 32bit mode on all platforms so the generated machine code on linux and mac with this example is 32bit.
the code i will post here is the was compiled under Apple clang with no optimization using -m32 flag to generate 32bit machine code
 #include <cstdio>

typedef unsigned long jmp_buf[6];

int Setjmp(jmp_buf var){
     __asm__(
             "    mov -4(%ebp), %eax     # get pointer to jmp_buf, passed as argument on stack\n"
             "    mov    %ebx, (%eax)   # jmp_buf[0] = ebx\n"
             "    mov    %esi, 4(%eax)  # jmp_buf[1] = esi\n"
             "    mov    %edi, 8(%eax)  # jmp_buf[2] = edi\n"
             "    mov    %ebp, 12(%eax) # jmp_buf[3] = ebp\n"
             "    lea   4(%esp), %ecx     # get previous value of esp, before call\n"
             "    mov    %ecx, 16(%eax) # jmp_buf[4] = esp before call\n"
             "    mov  (%esp), %ecx     # get saved caller eip from top of stack\n"
             "    mov    %ecx, 20(%eax) #jmp_buf[5] = saved eip\n"
             "    xor    %eax, %eax     #eax = 0\n"
     );

    return 0;
}

void Longjmp(jmp_buf var,int m){
    __asm__("    mov  -4(%ebp),%edx # get pointer to jmp_buf, passed as argument 1 on stack\n"
            "    mov  -8(%ebp),%eax #get int val in eax, passed as argument 2 on stack\n"
            "    test    %eax,%eax # is int val == 0?\n"
            "    jnz 1f\n"
            "    inc     %eax      # if so, eax++\n"
            "1:\n"
            "    mov   (%edx),%ebx # ebx = jmp_buf[0]\n"
            "    mov  4(%edx),%esi # esi = jmp_buf[1]\n"
            "    mov  8(%edx),%edi #edi = jmp_buf[2]\n"
            "    mov 12(%edx),%ebp # ebp = jmp_buf[3]\n"
            "    mov 16(%edx),%ecx # ecx = jmp_buf[4]\n"
            "    mov     %ecx,%esp # esp = ecx\n"
            "    mov 20(%edx),%ecx # ecx = jmp_buf[5]\n"
            "    jmp *%ecx         # eip = ecx");
}

void fancy_func(jmp_buf env);

int main() {
    jmp_buf env;
    int ret = Setjmp(env);
    if (ret == 0) {
        puts("just returning from setjmp!");
        fancy_func(env);
    } else {
        puts("now returning from longjmp and exiting!");
    }

}

void fancy_func(jmp_buf env) {
    puts("doing fancy stuff");
    Longjmp(env, 1);
}

i was following this tutorial : http://vmresu.me/blog/2016/02/09/lets-understand-setjmp-slash-longjmp/
Note: I've debugged the source code the problem comes from the:
 jmp *%ecx

but i think the problem is with setjmp and the way i'm storing the context
and specially that line:
 lea   4(%esp), %ecx     # get previous value of esp, before call\n"

which is also the part of the code that i'm not getting it.
i'm also aware of the code that was generated by my compiler for calling and cleaning the stack of setjmp and longjmp and the calling convention that was used (CDECL) in my case.
much thanks for any help .
Comment: C++ is not C is not C++! And that might be your problem. Why do you want to use them at all? Just don't. In C++, use exceptions, `setjmp` etc are some of the more problematic C legacies (when using C++) and they should be used with caution and.sparesly in C already.
Comment: Why are you programming in inline assembly? The stack layout is basically unpredictable from within inline assembly, you can't just assume that the compiler pushes the base pointer or anything like that.
Comment: Oh, and: read [ask] and follow the advice.
Comment: I want them for Coroutines that's why i've tagged C and C++
Comment: @jacky Then why don't you use the `setjmp` implementation in the libc?
Comment: @fuz I'm just curios about the real world implementation of those functions I've looked in libstdC++ but still can't get the some part of the code because of my assembly knowledge
Comment: @jacky I mean, that's fine, but please just write normal assembly instead of inline assembly. Inline assembly is a really easy way to shoot yourself into your foot because the compiler can change so many things.
Comment: @fuz you're right I actually don't write inline assembly in my code but why I'm using it here because it's the only way to do context switch any way using godbolt compiler explorer the compiler doesn't edit any part of the assembly code at least with no optimization on .
Comment: @jacky Why don't you use the C compiler installed on your system? You are just making things a lot more difficult for yourself. Note that when writing assembly, it actually doesn't matter what C compiler you use, so I really don't understand why you'd want to use godbolt.
Comment: @fuz I've mentioned that I've used three compilers on two different machines I took a look at the generated assembly by the compilers on my machine and on godbolt they're identical . look I just want to know the mistake I'm making in my code that's my big problem . any way thanks
Comment: @jacky The mistake is that what you do can't work in this manner. I mean, yeah, you can make it accidentally work by fumbling around until the stack layout is just right, but one option change and it breaks again. This code is unfixable in the way you wrote it. If you would use plain assembly, then I could surely tell you what the problem is, because then it's actually possibly to make this work in a reasonable manner.
Comment: @fuz  so if I get it right the implementation of setjmp and longjmp is back for the ABI developers of the compiler and stander library because they can let the code works in the right manner in any place ?
Comment: @jacky No. What I am trying to say is that just must stop using inline assembly for this purpose because the compiler chooses a stack layout in a basically unpredictable manner. Write this in pure assembly and we can talk. I am not even going to try and guess how the compiler chose to lay out the stack in your case, that would be a waste of time.
Comment: @jacky - A new option just arrived [Clang 5.0 has coroutines built into the compiler](http://releases.llvm.org/5.0.0/tools/clang/docs/ReleaseNotes.html#major-new-features). Now you don't *have to* hack it yourself.
Comment: @BoPersson thanks for the comment . Actually I've used boost.Coroutines before. the question was just out of curiosity and again thanks for the comment.
Answer: Many problems with this. As fuz said, you should not use inline assembly like this. Use separate asm file, or at least constraints and better not rely on a particular stack layout.
Anyway you got the offsets wrong, arguments are at positive offset from ebp not negative, with first being 8(%ebp). Also you got the return address wrong, it's at 4(%esp) since (%esp) is the saved ebp. Furthermore, since the function prologue saved ebp you are not saving the caller's ebp but a copy of esp.
The fixed version (still only works in 32-bit mode for calling conventions with stack args):
See the resulting asm for the whole function on the Godbolt compiler explorer
// optimize("no-omit-frame-pointer") doesn't seem to work
// we still don't get a frame-point unless we force -O0 for the function with optimize(0)
__attribute__((noinline, noclone, returns_twice, optimize(0)))
int Setjmp(jmp_buf var){
    // relies on the compiler to make a stack-frame
    // because we're using inline asm inside a function instead of at global scope
     __asm__(
             "    mov 8(%ebp), %eax     # get pointer to jmp_buf, passed as argument on stack\n"
             "    mov    %ebx, (%eax)   # jmp_buf[0] = ebx\n"
             "    mov    %esi, 4(%eax)  # jmp_buf[1] = esi\n"
             "    mov    %edi, 8(%eax)  # jmp_buf[2] = edi\n"
             "    mov    (%ebp), %ecx\n"
             "    mov    %ecx, 12(%eax) # jmp_buf[3] = ebp\n"
             "    lea    8(%ebp), %ecx  # get previous value of esp, before call\n"
             "    mov    %ecx, 16(%eax) # jmp_buf[4] = esp before call\n"
             "    mov    4(%ebp), %ecx  # get saved caller eip from top of stack\n"
             "    mov    %ecx, 20(%eax) #jmp_buf[5] = saved eip\n"
             "    xor    %eax, %eax     #eax = 0\n"
     );

    return 0;
}

__attribute__((noinline, noclone, optimize(0)))
void Longjmp(jmp_buf var,int m){
    __asm__("    mov  8(%ebp),%edx # get pointer to jmp_buf, passed as argument 1 on stack\n"
            "    mov  12(%ebp),%eax #get int val in eax, passed as argument 2 on stack\n"
            "    test    %eax,%eax # is int val == 0?\n"
            "    jnz 1f\n"
            "    inc     %eax      # if so, eax++\n"
            "1:\n"
            "    mov   (%edx),%ebx # ebx = jmp_buf[0]\n"
            "    mov  4(%edx),%esi # esi = jmp_buf[1]\n"
            "    mov  8(%edx),%edi #edi = jmp_buf[2]\n"
            "    mov 12(%edx),%ebp # ebp = jmp_buf[3]\n"
            "    mov 16(%edx),%ecx # ecx = jmp_buf[4]\n"
            "    mov     %ecx,%esp # esp = ecx\n"
            "    mov 20(%edx),%ecx # ecx = jmp_buf[5]\n"
            "    jmp *%ecx         # eip = ecx");
}

If you used an asm statement at global scope, you wouldn't need to fight against the compiler with __attribute__ stuff to make sure it emits the prologue you expect.  You could also skip setting up EBP so you'd have the caller's EBP directly.
asm(".globl SetJmp \n"
    "SetJmp:       \n\t"
    "   push   %ebp  \n\t"
    "   mov    %esp, %ebp  \n\t"

    "...  your current implementation    \n\t"

    "   xor    %eax,%eax   \n\t"
    "   pop    %ebp        \n\t"
    "   ret                \n\t"
 );

Comment: @fuz If there are no output operands then GCC assumes the asm statement is volatile and has undeclared side effects.
Comment: Note that depending on OPs compiler configuration, `-fomit-frame-pointer` may or may not be a default option (but it's impossible to tell). `__attribute__((naked))` could possibly help. I'm actually pretty surprised that the compiler doesn't just throw out the assembly as it has no side effects declared, but alas, that might just be the lack of optimizations.
Comment: @jacky The stack layout is pretty much unpredictable in all but the simplest situations. Try to avoid inline assembly if possible. It's full of pitfalls, very tricky to use correctly and often there are much better ways to achieve what you want to do.
Comment: @fuz: agreed, this would have broken horribly if compiled at anything other than `-O0`.  Fixed with `__attribute__((noinline, optimize(0)))`, and added an example of putting an `asm` statement at global scope.
Comment: @Jester thanks for the solution the code works fine. it seems i need to get more information about the stack layout that clang use in different situations. about the inline assembly thing as i said i don't use inline assembly that's my first time to use it i thought it's the right way to implement the functions because as i said i'm not experienced in Assembly and again thank you for helping

setjmp and longjmp implementation


Composition of Direct Image and Inverse Image

Question: I have two questions about Liu Qing's Algebraic Geometry and Arithmetic Curves. On page38, Lemma 2.23, there is an equation about a composition of direct image and inverse image:

$j_*(j^{-1}(\mathcal{O}_X/\mathcal{J}))=\mathcal{O}_X/\mathcal{J}$

I don't understand why it is true.
The second one is about $V(\mathcal{J})=\left\{x\in X |\mathcal{J}_x\neq \mathcal{O}_{X,x}\right\}$.
What is $\mathcal{J}_x\neq \mathcal{O}_{X,x}$ really mean?
Answer: (1) One doesn't have $\mathscr{G} \simeq f_*f^{-1}\mathscr{G}$ in general (example?) but there is always at least a morphism $\mathscr{G} \to f_*f^{-1}\mathscr{G}$ by adjointness and in this particular case you can check that it's an isomorphism on stalks, using the fact that if $i\colon Z \to X$ is the inclusion of a closed subset then the stalk  $(i_*\mathscr{F})_p$ is $\mathscr{F}_p$ if $p \in Z$ and zero otherwise.
More generally the same work shows that there is an equivalence between sheaves on $Z$ and sheaves on $X$ with support contained in $Z$.
(2) Whenever you have a subsheaf $\mathscr{F}'$ of $\mathscr{F}$ there is a natural inclusion of stalks $\mathscr{F}'_p \subset \mathscr{F}_p$. You can then ask whether equality holds at certain points.
Maybe it would be good to try this with an explicit example of a closed embedding, just to see what the maps in (1) and (2) look like.


I dont know what does sudo su bash mean

Question: I want to run amun honeypot on Ubuntu 13.10 and I sometimes have problem with running this honeypot. I just write this command $ sudo ./amun_server.py & but it cant work sometimes. I want to try this command sudo su bash but I don't know what this command can do.
Comment: Related: [What is the difference between 'su -' , 'sudo bash' and 'sudo sh'?](http://askubuntu.com/questions/57040/what-is-the-difference-between-su-sudo-bash-and-sudo-sh)
Answer: When you type:
 sudo <command>

you are running  as root user, the requested password is your password. Only your uid is changed and the environment is the same as your user.
When you type:
 su

su command without parameter allow user to become superuser. In this case the requested password is about root.
When you type:
 sudo su

you are running su as root user, sudo ask your password and su does not. So you can become root without knowing the password.
Caution: It is strongly recommended to not use this command unless you really know very well what you are doing
If you want exec command as another user login shell environment:
 sudo su - <user> -c <command>

or
 sudo -u <user> -i <command>

Here is useful link
Comment: Hi Letizia it was so usefull thannks for your answer
Comment: @ Shahrzad Torabi zadeh if this is what you are looking for, update your question as requested and clarify what you need. This will help other people that have same problem to find out more easly information they need.
Answer: Hi Why not open a terminal Ctrl + Alt + T and type man su? That will explain what the su command does.
Similarly with bash.
man = manual and it gives a list of arguments that can be used with the command.

I dont know what does sudo su bash mean


Filtering Active Directory Users in Alphabetical Order

Question: I've got to modify a property in active directory for each user throughout the company I work for.  This is the code that I am user to get all users.
<code>        String domain = Properties.Settings.Default.ADConn;
        String user = Properties.Settings.Default.ADAdmin;
        String pass = Properties.Settings.Default.ADPass;

        DirectoryEntry ADEntry = new DirectoryEntry(domain, user, pass);
        DirectorySearcher ADSearcher = new DirectorySearcher(ADEntry);
        ADSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
        SearchResultCollection allResults = ADSearcher.FindAll();
        foreach (SearchResult result in allResults)
        {
            DirectoryEntry deUser = result.GetDirectoryEntry();

             //....Do stuff here
</code>
There are a large amount of people in the company, and so it was requested that I split the users alphabetically and handle one chunk of users at a time.  For example, change properties for users [A-G], then [H-N], then [O-Z].  How can I modify my filter to give me users X through Y?
EDIT: My Final result was to do the following:
<code>ADSearcher.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName>=X)(sAMAccountName<=Y))";
</code>
Thank you very much for your help.
Comment: To clarify, by "users X through Y" I mean users whose last names or possibly samaccountnames start with X through users whose last names or possibly samaccountnames start with Y.
Answer: I have used OpenLDAP before so I am little bit familiar with filters and I found a Search Filter Syntax document which might help. Here is what I think might be possible:
<code>(&(objectClass=user)(objectCategory=person)(cn>='a')(cn<='b'))
</code>
Let me know if it works.
Comment: I believe you need to drop the quotes around the letters.  So a **LastName** search would be:    `(&(objectClass=user)(objectCategory=person)(sn>=m)(sn<=p))`  A **username** search would be: `(&(objectClass=user)(objectCategory=person)(sAMAccountName>=m)(sAMAccountName<=p))`
Comment: Both of you together are correct.  This worked perfectly.  Thank you very much.


need quiet refrigerator for living room

Question: We have an open-plan living room / kitchen. We installed IKEA furniture in the kitchen (Metod / Bobdyn). We have to choose a built-in fridge / freezer. For this IKEA kitchen one can only install
54cm * 54cm (width * depth) freezers.
Our biggest concern is noise.
We already tried Whirlpool ART9811 SF, and that was disappointingly noisy. It was advertised as 35dB, but when the compressor was on maximum level (after loading lots of stuff into) it was audible in the whole house for hours. Even when the compressor was off, there was a loud sloshing sound for hours. In the living room it was simply annoying. Fortunately we could send it back to the shop. It was not installed in the cabinet, but was leveled.
Then we tried AEG SCE618E5TS. It was advertised as 36dB, but was a LOT quieter than the Whirlpool. Still the no-frost fan was too noisy. We bought it with the option to send back...
Now I would really want to find an acceptable one.
The ideal one would be a SILENT fridge / freeze with ~200l fridge and ~70l freeze compartment. For me silent means that I can read a book on the sofa 5m away from the fridge without noticing that it is on.
How can I choose such a fridge?
What kind of compressor / fan / etc should I search for?
Are there recommended manufacturers for silent fridges maybe?
Will the IKEA cabinet absorb noise significantly? I checked the documentation, and there must be a sizable opening at the bottom and the top of the cabinet for air circulation, I am worried that noise will leak through there and there will be no real noise reduction.
Is no-frost technology neccessarily noisy? As far as I understood no-frost means a fan in the freeze section which circulates air. To me it seems easy to manufacture an almost noiseless fan (compared to manufacture a silent compressor), but maybe that's not the case?
Are fridges without freeze section significantly quieter? We started thinking on buying a fridge without freezer for the living room - kitchen, and put a freezer into the basement. Is it a good idea?
Should we look for stand alone fridges instead of the built in? A stand alone one would not look as good as a built in, but if that is the price for low noise than we would pay it.
Thanks for your help!
Comment: FYI as I have tried similar things, any cabinet you use, will heat up fridge and make it louder.
Comment: If you happen to have a home stereo system, take a close look a the speakers. You'll note that they are made of cones which vibrate based on the signal sent to them _and reverberate inside a wooden box_. The box is integral to the amplification of the sound. You're putting something that's going to make _some_ noise into a speaker box and expecting this to suddenly be quiet. You'd have to foam pad the fridge surround to absorb the noise, but still allow for air flow if you are to have a hope of quieting the fridge.
Answer: The only way you might be able to achieve that would be with a split refrigerator (compressor located elsewhere, preferably outdoors), and that's a very expensive custom deal. Quite normal for "walk-in refrigerators" seldom seen in a house-scale application.
There's the Peltier junction option, but it's laughably inefficient and will do a great job heating your house whether you want it to or not. "No moving parts - solid state" but truly laughably inefficient, and generally not available in a normal size fridge anyway.
Comment: That probably has something to do with "being used to its noises and ignoring them" as well as any objective measurement of noise level. I can hear my fridge running more than 5m away, but I can also sleep through my fridge running quite easily. It certainly makes audible noises of various sorts - I'm just used to them, so they are not **noticeable**. A different fridge would make different noises. Most appliance ratings use a deceptive weighting for noise level (long averaging time, so if it makes loud noises but only a little bit of the time, it still gets a low number...)
Comment: Peltier or split refrigerator is obviously not an option for us. I don't want a noiseless fridge. I want one which is at least as quiet as the old (~20 years old) Snaige stand alone fridge we are replacing. That fridge was not noticeable to me 5m away.

need quiet refrigerator for living room


Flush DNS using Java

Question: The usual command for flushing the system dns using command prompt is ipconfig/flushdns.
Is there anyway to do the same flush operation from java? Any java function to perform the same flush dns operation?
Answer: You may want to run the same command using Java as:
<code>     Process p= Runtime.getRuntime().exec("cmd /c ipconfig /flushdns");
</code>
Comment: Its the same? I mean does it do the same operation?
Comment: @VarunNatraaj: Using the above syntax, you should be able to execute Windows command line operations through Java. "ipconfig/flushdns" shouldn't be any exception.

Flush DNS using Java


Moving casper-rw to another partition

Question: I'm creating a multiboot flash drive with several linux distros on it that I boot from grub2. I currently have a live Ubuntu install set up where casper-rw is on the same partition as Ubuntu live; because I have several different distros with persistence, I am using the persistent-path boot parameter to keep them separate, which is working fine.
The partition where Ubuntu is installed is a FAT32 partition, though, and I'd like to move casper-rw to a separate ext2 partition to get around the 4Gb file size limitation.  I can't figure out how to do that.  I tried doing something like persistence-path=/dev/sdb2/ubuntu (and put casper-rw in that directory), but it doesn't seem like persistence-path knows how to navigate devices (I get an error that looks like it's from overlayfs about lowerdir being invalid when I do that).
In other distros I'm able to tell it which device to put the persistence file on, and it can be separate from the device where vmlinuz lives.  Is this possible with Ubuntu?  If so, how?  Just to be clear, I DON'T want to create a casper-rw partition (since I want separate casper-rw files for each of my distros).  I just want to be able to tell grub which partition to look on for my persistence file, where that partition is different from the one where my Ubuntu system files live.
Comment: YUMI has a method that allows casper-rw files over 4GB. I believe that it creates a casper-rw file that is like a virtual ext4 partition, with the help of grub4dos. I will look through my stuff to see if I ever got it working with persistent-path. I know I never got persistent partitions working with persistent-path.
Answer: YUMI Multi Boot
YUMI will make a Multi Boot USB with multiple persistent files larger than 4GB. Persistent=path is not required.
There is a version for BIOS Boot and a Version for UEFI Boot.
For casper-rw files greater than 4GB start with a NTFS formatted drive.
If my memory is correct, the UEFI version is FAT32 only and does not work for large casper-rw files.
https://www.pendrivelinux.com/yumi-multiboot-usb-creator/
See also: Casper-rw files larger than 4GB - please confirm
Multi Boot Full Install USB BIOS/UEFI
Now days USB flash drives are getting large and saving room booting squash file systems and ISO's is not so important.
Mkusb makes a great base for custom Multi Boot USBs. The following shows how to make a Full install USB, that boots both BIOS and UEFI and then further modify it as a Multi Booter, (that even boots ISOs using grub2).

Use mkusb to make a Live system on the Installer USB (2GB or larger).
Use mkusb to make a Persistent system on the Target USB using default settings with >25GB persistence, (remaining NTFS partition is used as Windows accessible data partition). Select upefi to insure grub 2.02 for ISO booting.

As soon as mkusb finishes, open GParted and delete sdx4, the ISO9660 partition and expand sdx5 into the recovered space, sdx being the device name of the Target drive.

Unplug or remove HDD before proceeding further, (optional but highly recommended in UEFI mode).
Boot Installer drive, select Try.
Insert Target drive

Start Install Ubuntu...

Select Something else.
Select sdx5, (on the target drive), and click Change.

Select Use as: ext4, Format and Mount point: /.

Don't touch any other partitions (unless adding a /home partition).

Select sdx5 as Device for boot loader installation.
Complete installation.
Cut grub.cfg from sdx5/boot/grub and paste to sdx3/boot/grub, overwriting the existing grub.cfg file.
Boot the target drive and run sudo update-grub to add all drives to boot menu.

Multi Boot
Multiple OS, both Full install and Live/Persistent can be added to the USB.
Create a drive as suggested above, then divide the expanded partition into parts, (sdx5, sdx6, sdx7... in this case).
You can then install Ubuntu on one partition and other OS on the other partition(s).

Divide sdx5 into as many ext4 partitions as you have OS. Size should be about 8GB each or larger.
Boot Live mkusb installer and insert the target drive.
At partitioning selected "Something else".
Choose sdx5 for /.
Install bootloader to sdx5.
Leave all other partition's format boxes unchecked.
Repeat this with sdx6, sdx7, etc, and the OS's you choose to install.
After the last install cut grub.cfg from sdx6/boot/grub and paste to sdx3/boot/grub, overwriting the existing grub.cfg file.
Boot the flash drive and do an update-grub. This will add all the OS to grub.

You can add a few OS ISO's if you wish:

Create a folder in the NTFS partition sdx1 named isos.
Add a few ISO's.
Edit sdx3/boot/grub adding menuentries similar to the following:
<code>menuentry "xubuntu-18.04.1-desktop-amd64 Partition 6" {
 set isofile="/isos/xubuntu-18.04.1-desktop-amd64.iso"
 set root='(/dev/sdx,msdos2)'
 search --no-floppy --fs-uuid --set=root XXXX-XXXX
 loopback loop ($root)$isofile
 linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile noprompt noeject
 initrd (loop)/casper/initrd.lz
}
</code>
Substitute your sixth, (seventh and eighth), partition's UUID for XXXX-XXXX
vmlinuz may need to be vmlinuz.efi for some versions.
Each ISO can have it's own casper-rw and home-rw persistence files if desired, but it starts to get a little more complicated as you need to add the "persistent-path" to each menuentry.

If ISO booting is anticipated use pre 19.10 grub 2.02 as grub 2.04 is not working for booting ISO's
Comment: When I originally set this up I researched all the various multiboot tools, and for various reasons I don't think YUMI works for me.  There are a few reasons - I need both BIOS and UEFI support, not one or the other, and I have also installed various Windows preboot environments on it as well, plus installing a few full linux distros that aren't isos, etc.

The idea about using an NTFS partition is interesting though.  Are you saying that it's possible to install a live ubuntu image to an NTFS partition? I didn't think NTFS was supported well for Linux?
Comment: I have tried casper-rw on a NTFS partition using UNetbootin, MultiBootUSB and a few others, without success. (Sundar suggested MBUSB might work with NTFS >4GB, but it did not work for me). The NTFS method used by YUMI only works with BIOS boot. Rufus 3.8 allows an ext3 persistent partition > 4GB for Ubuntu 19.10, and later, both BIOS and UEFI. Rufus only allows one OS per disk. One solution that might work for you is to make Full installs to USB rather than Persistent.  If you find a solution please post your solution here, I have been interested in this subject a long time.

Moving casper-rw to another partition


how to edit an existing row value on the basis of the previous row value in python

Question: I have a dataset as below:
date time value
20141102 1420 0
20141102 1425 2
20141103 1430 N/A
20141103 1435 N/A
20141104 1440 2
20141104 1445 N/A
20141105 1450 N/A
20141105 1455 2

But I want to edit the column value.
1. I want the value to be 0 instead of 2 if the previous value is N/A. The desired output should be like this:
 date time value
 20141102 1420 0
 20141102 1425 2
 20141103 1430 N/A
 20141103 1435 N/A
 20141104 1440 0
 20141104 1445 N/A
 20141105 1450 N/A
 20141105 1455 0

Answer: np.where + shift
df['value']=np.where(df.value.isnull().shift()&df.value.eq(2),0,df.value)
df
Out[593]:
       date  time  value
0  20141102  1420    0.0
1  20141102  1425    2.0
2  20141103  1430    NaN
3  20141103  1435    NaN
4  20141104  1440    0.0
5  20141104  1445    NaN
6  20141105  1450    NaN
7  20141105  1455    0.0


Can't upgrade Ubuntu 16.04.5 LTS to 18.04.1 LTS because can't upgrade libbluray-bdj

Question: I am unable to upgrade from Ubuntu 16.04.5 LTS to 18.04.1 LTS because one package has not been upgraded (libbluray-bdj). When I try to upgrade it, it can't be upgraded because it depends on a package (libasm-java) that is not upgradable because it has no installation candidate. When I try to remove libbluray-bdj, it tells me it will remove ubuntu-mate-desktop which I don't want to do.
I was performing the upgrade via the terminal because I did a partial upgrade through Software Updater previously (before I ran into these problems), and I don't want to leave my system in a partial uprade state between 16.04.5 and 18.04.1.
I just want to upgrade to 18.04.1. Thanks!
Here are the commands I used and their outputs:
lsb_release -a

No LSB modules are available.
  Distributor ID: Ubuntu
  Description:    Ubuntu 16.04.5 LTS
  Release:    16.04
  Codename:   xenial

sudo apt update && sudo apt upgrade

1 package can be upgraded. Run 'apt list --upgradable' to see it.

apt list --upgradable -a

libbluray-bdj/xenial,xenial 1:1.0.2-3~xenial all [upgradable from: 1:0.9.2-2]
  N: There is 1 additional version. Please use the '-a' switch to see it

sudo apt-get dist-upgrade

0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

sudo apt-get upgrade -y

The following packages have been kept back:
      libbluray-bdj
  0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.

sudo do-release-upgrade

Please install all available updates for your release before upgrading.

sudo apt-get dist-upgrade libbluray-bdj

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  Calculating upgrade... Error!
  Some packages could not be installed. This may mean that you have
  requested an impossible situation or if you are using the unstable
  distribution that some required packages have not yet been created
  or been moved out of Incoming.
  The following information may help to resolve the situation:
The following packages have unmet dependencies:
   libbluray-bdj : Depends: libasm-java but it is not installable
  E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

sudo apt-get dist-upgrade libasm-java

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  Package libasm-java is not available, but is referred to by another package.
  This may mean that the package is missing, has been obsoleted, or
  is only available from another source
E: Package 'libasm-java' has no installation candidate

 sudo apt-get remove libbluray-bdj

The following packages will be REMOVED:
    libbluray-bdj ubuntu-mate-desktop

and I don't want to remove ubuntu-mate-desktop.
UPDATE:
Here are the contents of /etc/apt/sources.list:
$ cat /etc/apt/sources.list
# deb cdrom:[Ubuntu-MATE 16.04.2 LTS _Xenial Xerus_ - Release amd64 (20170215)]/ xenial main multiverse restricted universe

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://us.archive.ubuntu.com/ubuntu/ xenial main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ xenial universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial universe
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://us.archive.ubuntu.com/ubuntu/ xenial multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial multiverse
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu xenial partner
# deb-src http://archive.canonical.com/ubuntu xenial partner

deb http://security.ubuntu.com/ubuntu xenial-security main restricted
# deb-src http://security.ubuntu.com/ubuntu xenial-security main restricted
deb http://security.ubuntu.com/ubuntu xenial-security universe
# deb-src http://security.ubuntu.com/ubuntu xenial-security universe
deb http://security.ubuntu.com/ubuntu xenial-security multiverse
# deb-src http://security.ubuntu.com/ubuntu xenial-security multiverse

Comment: I don't have an answer for this, but I had noticed that [https://packages.ubuntu.com](https://packages.ubuntu.com) was behaving poorly yesterday.  Today it does not show  'libasm-java' in Xenial, although it does appear in Trusty and Bionix.  I think you could wait it out (ugly) or contact the server administrator "firstname.lastname@example.com"
Comment: Can you append to your question, the contents of  `/etc/apt/sources.list`
Comment: Contents of /etc/apt/sources.list appended.
Comment: It appears that the package is back and available now - Please try `sudo apt update && sudo apt upgrade` again
Comment: Well sort of.  You can download the correct package from [https://packages.ubuntu.com/trusty/all/libasm-java/download](https://packages.ubuntu.com/trusty/all/libasm-java/download), and use the software center to open and install the package.
Answer: Spend enough time really absing Ubuntu and you'll hit dependencies issues like this.
I have a whole boatload of PPAs installed at any given moment so upgrades are often quite fun. That isn't your problem —it looks like there's a missing package in the repo for whatever reason, and I have options like ppa-purge— but my typical approach to fixing is what I'd recommend to you...

Remove any problematic packages. Yes, even the ubuntu-mate-desktop meta-package.
Do your upgrade but don't do the package clean-up it offers at the end. Not a disaster if you do.
Reboot. Hopefully you're still on a desktop but even if you aren't, find your way to the nearest terminal and sudo apt install ubuntu-mate-desktop.
If you managed to hold of the stage-2 cleanup, it's time to run sudo apt autoremove to remove automatic packages that aren't required any more.

It's scary, it looks wrong, but packages can be removed and reinstalled and nothing is lost forever. Your desktop config lives in your $HOME and isn't part of the remove. System settings in /etc/ aren't removed by apt remove (that's purge's job). You might end up at a command line. You might need nmtui to get yourself connected at the other side, but it's all relatively low risk.
I think you've identified why this has happened. Some sort of fruity bug in libasm-java, or the packaging of it, that is blocking everything around it. This won't affect you in 18.04 because ubuntu-mate-desktop` no longer depends on it.

I'd like to think that this answer is transferable to any instance where you're up against a package conflict but be conscious of what it is you're removing.
In this case it's a crufty old Bluray library and a meta-package for a desktop environment. If you start seeing important things like network-manager or linux-image pop up in the "going to be REMOVED" warning, take a step back and start a new question :D


Is value returned by java.util.Date.getTime() same as java.time.ZonedDateTime.getEpochSeconds()?

Question: I have a legacy application that is passing Date using

java.util.Date

and a new service that is providing date using

java.time.ZonedDateTime

.
My use case is to compare both the dates and determine which one is most recent.
Can I use java.util.Date.getTime()/1000 and java.time.ZonedDateTime.getEpochSeconds() and compare the resulting values from both these methods?
Am I missing anything by comparing the seconds from both of these packages?
Comment: If you have `java.util.Date a` try `ZonedDateTime a1 = ZonedDateTime.ofInstant(a.toInstant(), ZoneId.systemDefault());` and compare two `ZonedDateTime`(s). `java.util.Date` is broken. Replace it as soon as you can.
Comment: You comparison loses precision but is otherwise correct (only inaccurate).
Answer: tl;dr
myJavaUtilDate
.toInstant()
.isBefore(
    myZonedDateTime
    .toInstant()
)

Instant
As commented, the most graceful approach uses java.time.Instant. That class represents a moment as seen in UTC with a resolution of nanoseconds.
Convert
The java.util.Date is a terribly flawed class that is now legacy. Avoid whenever possible. But if handed an object if that class,  call the new conversion methods added to the old legacy date-time classes.
Be aware that Date has a resolution of mere milliseconds.
Instant x = myJavaUtilDate.toInstant() ;

And your ZonedDateTime object can be adjusted to UTC by extracting an Instant. Both of these classes resolve to nanoseconds.
Instant y = myZonedDateTime.toInstant() ;

Compare
Compare with isBefore or IsAfter methods.
if ( x.isBefore ( y ) ) { … }


Finding the super-mean (NOT the mean) of a set of numbers.

Question: the super-mean is found by grouping pairs of numbers and finding the average successively
until there is just one number. For example,
$$(1-2-3-4-5) \to ((1+2)/2,(2+3)/2,(3+4)/2,(4+5)/2) \\
(1.5,2.5,3.5,4.5) \to(1.5+2.5)/2,(2.5+3.5)/2,(3.5+4.5)/2) \\
(2.0,3.0,4.0) \to2.5,2.5)$$
Then the super-mean is 3.0.i suspect a relationship between these problems and pascal triangles, then binomial coefficients, how to find the super-mean out of the set of numbers. I have read that the super-mean is given by:
$$S_{n} = \left(\frac{1}{2^{n-1}}\right)\sum_{i = 0}^{n-1}\binom{n - 1}{i}a_{i}$$
$n$ is the size of the input $[0, \ldots, n]$.
$(1,2,3,4,5) \to n = 4$
How can I relate the problem with this formula, how do i derive the formula for the super-mean.?. Is there any reading material for these kind of problems?
Answer: The supermean is a mean of the number with coefficients.
To find out the coefficient $p_k^n$ of the $k^{th}$ item of a sequence $a_0\dots a_n$, it suffices to see that this number contributes in two ways in the next step (except for $a_0$ and $a_n$ which are on the sides).
Therefore we have the induction formula:
$$p_k^n=p_{k-1}^{n-1}+p_{k}^{n-1}$$ with the base cases $p_{-1}^n=p_{n+1}^n=0$ and $p_0^n=p_n^n=1$ for all $n$.
This means we get exactly the  induction formula for the binomial coefficients, and indeed your formula for $S_n$ is good.


bash loop same variable from multiple configs

Question: I'm trying to loop same variables from multiple files in bash. Here's my file structure and their contents;

script.sh
first.conf
second.conf

Inside of first.conf;
var=Hello1

Inside of second.conf;
var=Hello2

Inside of script.sh;
#!/bin/bash

_a=`find ~/ -name "*.conf"`

source ${_a}

for x in ${_a}
do
  echo "$var"
done

This might look really dumb tho, I'm really new to programming.
What I'm trying to do is to loop and echo these $vars from 2 different configs.
How can I do that?
Comment: Storing output from `find` in a single string isn't always a great idea in and of itself. Look at what happens when your filenames have spaces, or -- even worse -- if the files contain newlines. `find` returns multiple results; an array is the native approach to storing several strings in bash (and using NUL rather than newline delimiters lets you distinguish between newlines added as separators by `find` and newlines that are part of the filenames themselves).
Comment: Thank you for your wise words, I'll definitely take them into consideration during my learning process.
Answer: Consider:
while IFS= read -r -d '' conf; do
  (source "$conf" && echo "$var")
done < <(find ~ -name '*.conf' -print0)

Breaking down how this works:

The while read syntax is discussed in BashFAQ #1. The variant with -d '' expects input separated by NULs rather than newlines -- more on that later.
Putting (source "$conf" && echo "$var") in parens prevents side effects on the rest of your script -- while this has a performance cost, it ensures that variables added by source are only present for the echo. Using the && prevents the echo from running if the source command fails.
<(...) is process substitution syntax; it's replaced with a filename that can be read to retrieve the output of the command therein (in this case find). Using this syntax rather than piping into the loop avoids the bugs discussed in BashFAQ #24.
The -print0 action in find prints the name of the file found, followed by a NUL character -- a zero byte. What's useful about NUL bytes is that, unlike any other ASCII character, they can't exist in UNIX paths; using them thus prevents your code from being subject to trickery (think about someone running d=$'./tmp/\n/etc/passwd\n' && mkdir -p -- "$d" && touch "$d/hi.conf" -- traditional find output would have /etc/passwd showing up on its own line, but with find -print0, the newlines in the name aren't mistaken for a separator between files.
Answer: This is a shorter and simpler way.
#!/bin/bash

for f in *.conf
do
        source "$f"; echo "$f : $var"
done

Comment: `source "$f"` to be reliable with files that have spaces in their names. And without either `find` or `shopt -s globstar` followed by `**/*.conf`, it won't search subdirectories (which the OP's original code did).
Comment: Thanks for the comments Charles.}


Jacobi identity as a cocycle condition

Question: The Jacobi identity in a Lie algebra $\mathfrak{g}$ looks like this (for $x,y,z\in \mathfrak{g}$):
$$[[x,y],z]-[x,[y,z]]+[y,[x,z]]=0.$$ This just says that the map $y\mapsto [x,y]$ is a derivation with respect to the Lie bracket $[-,-]$.
It also looks like some sort of cocycle condition. An alternating sum equal to zero. Can this be made precise? Is the Jacobi identity the kernel of some differential?
Comment: Sorry Mariano you probably know but.... This is a complete answer to the question, not just a comment. Please post your answer as an answer. This brings extra visibility to the answer und puts the question off the unanswered list (otherwise it will be bumped up periodically). Comments should only be used to clarify the problem. https://math.stackexchange.com/help/privileges/comment
Answer: For the adjoint $\mathfrak{g}$-module $\mathfrak{g}$ we have
$$
Z^1(\mathfrak{g},\mathfrak{g})={\rm Der}(\mathfrak{g}),\quad B^1(\mathfrak{g},\mathfrak{g})={\rm ad}(\mathfrak{g})
$$
for the Lie algebra cohomology. So the map ${\rm ad}(x)$, defined by $y\mapsto [x,y]$ is a $1$-cocycle for the Lie algebra cohomology with coefficients in the adjoint module. In this sense, the Jacobi identity is a derivation condition, which is a $1$-cocycle condition.
In general,
the space of Lie algebra $1$-cocycles and $1$-coboundaries with coefficients in a $\mathfrak{g} $-module $M$ is given by
\begin{align*}
Z^1(\mathfrak{g},M) & = \left \{ \omega \in Hom (\mathfrak{g},M) \mid \omega ([x,y])=
x\cdot \omega (y)-y\cdot \omega(x) \right \}\\
B^1(\mathfrak{g},M) & = \{ \omega \in Hom (\mathfrak{g},M) \mid \omega (x)=x\cdot m
\mbox{ for some } m\in M \}
\end{align*}
Comment: @MarianoSuárez-Álvarez Yes, I agree. But the formulation "it looks like some sort of cocycle condition" is not so specific about it, so that I thought, viewing a derivation as a $1$-cocycle is a possibility.

Jacobi identity as a cocycle condition


Give examples of a formal power series $\sum_{n=0}^\infty c_n x^n$ centered at $0$ with radius of convergence $1$.

Question: Give examples of a formal power series $\sum_{n=0}^\infty c_n x^n$ centered at $0$ with radius of convergence $1$, which
(a) diverges at both $x=1$ and $x=-1$;
(b) diverges at $x=1$ but converges at $x= -1$;
(c) converges at $x=1$ but diverges at $x=-1$;
(d) converges at both $x =1 $ and $x =-1$;
(e) converges pointwise on $(-1, 1)$, but does not converges uniformly on $(-1, 1)$.
For (a), $c_n$ can be any constant real number or $c_n = n$ also works.
For (b), $c_n = \frac1n$ works.
For (c), $c_n = (-1)^n \frac1n$ works.
I have difficulty in coming up with examples for (d) and (e). Can you give me some hint?
Answer: $\sum \frac 1 {n^{2}} x^{n}$ has radius of convergence $1$ and it converges at both $x=1$ and $x=-1$.
$\sum  n x^{n}$ converges for $|x|<1$ but the convergence is not uniform since the general term does not tend to $0$ uniformly (as seen by putting $x=\frac 1 {n^{1/n}}$).


Java - Lock Aspect Ratio of JFrame

Question: Is it possible to lock the aspect ratio of a JFrame in Java Swing?
For example, if my window is 200px by 200px, and the user wants to resize it, I want the ratio between the width and the height at 1:1, so that if the new width is 400px, the new height is forced to 400px.
I'm aware of ComponentListener and componentResized, but I'm having difficulty not getting it to go into an infinite loop of resizing, because I'm resizing the window in a resize listener.
Thanks!
Answer: I don't have a specific answer to your question, but I have often found that the way to avoid the "infinite loop of resizing" you talk about is to defer your call to resize the window:
boolean correctAspectRatio = ...; // check to see if new size meets aspect ratio requirements

if (!correctAspectRatio) {
  final Frame _frame = this;
  final int _width = ...; // calculated width
  final int _height = ...; // calculated height

  SwingUtilities.invokeLater(new Runnable(){
    public void run() {
      _frame.setSize(_width, _height);
    }
  });
}

Comment: Even if I do this, it will still go into a loop of resizing, it's just not as noticeable. Try doing _width + 20, _height + 20, and you'll see what I mean.
Comment: I am assuming you don't call the resize if the size meets the aspect ratio, right? See my edited answer
Comment: Ah, that worked great. I suppose there really isn't much of a way to do this while the user is resizing, but this way works fine. Thanks.

Java - Lock Aspect Ratio of JFrame


How to return the last value in Q javascript

Question: Hi there im new to writing promises in javascript. I want to return a value from func1 which are composed of then (using q) calling other functions resolving the value then passing to through the next function. The problem is i want to return the last value in func 1. So I can use it in caller function. But init value just returns undefined.
Here are the codes:
function func1(string1, string2) {
  othermodule
    .otherfunc1(string1)
    .then(function(outputstring1) {
      var params = othermodule.otherfunc2(outputstring1,string2);
      return params;
    })
    .then(anotherfunc)
    .then(anotherfunc2)
    .then(function (data) {
       console.log(data);
       // outputs data
       return data;
    });
}

function caller() {
  var initValue = 0;
  initValue = func1(string1,string2);
  console.log('init value = '+initValue);
  //init value = undefined
}

Comment: promises do not make asynchronous code synchronous ...
Comment: In this case i want to return data such that initValue = data
Comment: how to resolve then?
Answer: Writing asynchronous code in javascript is poisonous, meaning all code calling async code must be async itself.
Your code can be rewritten to:
function func1(string1, string2) {
    return Q.fcall(othermodule.otherfunc1, string1)
        .then(function(outputstring1) {
            var params = othermodule.otherfunc2(outputstring1, string2);
            return params;
        })
        .then(anotherfunc)
        .then(anotherfunc2)
        .then(function(data) {
            console.log(data);
            return data;
        });
}

function caller() {
    return func1(string1, string2).then(function(initValue) {
        console.log('init value = ' + initValue);
    });
}

Comment: what is the difference of using Q.fcall? isn't it just the same?
Comment: also this gives out unexpected token return on the return func1
Comment: `Q.fcall` seems superfluous in this code as `othermodule.otherfunc1` already returns a promise
Comment: @JaromandaX I wasn't sure that `othermodule.otherfunc1` returns a promise.
Answer: Return the promise in func1
and use .then in caller to get the "returned" value
function func1(string1, string2) {
    return othermodule.otherfunc1(string1)
        .then(function(outputstring1) {
            var params = othermodule.otherfunc2(outputstring1, string2);
            return params;
        })
        .then(anotherfunc)
        .then(anotherfunc2)
        .then(function(data) {
            console.log(data);
            return data;
        });
}

function caller() {
    func1(string1, string2).then(function(initValue) {
        console.log('init value = ' + initValue);
    });
}

Comment: sorry got it now I forgot to put return on the othermodule.otherfun1(string1) thanks! :)
Comment: the problem is I want to get the data outside the promise. Is there no method to return this? If I do the way you did then I will still be inside the promise.
Comment: You have to deal with the asynchronous nature of the code - you can't turn it synchronous. Embrace the asynchronous nature of javascript, it's not that hard to change how you code
Comment: @user1727843 - is there a problem with the answer or how you are using it?


change Right to End for RTL layouts but layout-v17 was created

Question: I have this in res/layout
<code><TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/txt"
    android:layout_alignBottom="@+id/txt"
    android:layout_toRightOf="@+id/txt"
    android:text="@string/..."
    android:layout_marginLeft="3dp"
    android:textAppearance="?android:attr/textAppearanceSmall" />
</code>
and it tells me to change layout_toRightOf to layout_toEndOf and layout_marginLeft to layout_marginStart to better support right to left layouts. I did that but because of conjunctions, I created a new layout-v17 folder and made 2 versions, one for each API modes.
If I understand correctly, Android will take the relevant layout depending on the API it runs on, right? so how can I tell it not to warn me anymore about the 2 attributes from the older API (original res/layout folder)?
Answer: Right click on your android
properties->Java Compiler->Errors and warnings->Deprecated and restricted API->Discouraged reference
change this reference to ignore. If this not work some other setting will work under errors and warnings.


Chef warning "Did not find config file: /solo.rb. Using command line options instead."

Question: I was trying to install apache2 server in a vagrant machine. Ubuntu 16.04 is my vagrant-box and using chef as infrastructure provision tool. When I tried to execute sudo chef-solo -c solo.rb command the follwing warring shown and nothing installed.
vagrant@chef:/vagrant$ sudo chef-solo -c solo.rb
[2019-05-23T15:01:24+00:00] WARN: *****************************************
[2019-05-23T15:01:24+00:00] WARN: Did not find config file: /solo.rb. Using command line options instead.
[2019-05-23T15:01:24+00:00] WARN: *****************************************
[2019-05-23T15:01:24+00:00] WARN: No cookbooks directory found at or above current directory.  Assuming /var/chef.
[2019-05-23T15:01:24+00:00] WARN: *****************************************
[2019-05-23T15:01:24+00:00] WARN: Did not find config file: /solo.rb. Using command line options instead.
[2019-05-23T15:01:24+00:00] WARN: *****************************************
Starting Chef Client, version 14.12.9
resolving cookbooks for run list: []
Synchronizing Cookbooks:
Installing Cookbook Gems:
Compiling Cookbooks...
[2019-05-23T15:01:28+00:00] WARN: Node chef has an empty run list.
Converging 0 resources

Running handlers:
Running handlers complete
Chef Client finished, 0/0 resources updated in 02 seconds

here is my project directory structure:-

node.json :-
{
    "run_list":[
        "recipe[webserver::install_apache]"
    ]
}

Recipe to be cooked is install_apache.rb:-
package "apache2" do
    action :install
end
# A resource
service "apache2" do
    action [:start,:enable]
end

The configuration file solo.rb:-
CHEF_ROOT="/vagrant"
cookbook_path "#{CHEF_ROOT}/cookbooks"
json_attribs "#{CHEF_ROOT}/node.json"

I have checked the permission of solo.rb, cookbooks directory and found everything ok.
chef --version :-
Chef Development Kit Version: 3.10.1
chef-client version: 14.12.9
delivery version: master (9d07501a3b347cc687c902319d23dc32dd5fa621)
berks version: 7.0.8
kitchen version: 1.24.0
inspec version: 3.9.3

I  I have just started to learning Chef and have not found any hint why that warning happening!
Answer: On Ubuntu 18.04 or other linux distro, passing the canonical path only made it works.
sudo chef-solo -c $PWD/solo.rb -j $PWD/mconf-live-standalone.json
Example :
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$ sudo chef-solo -c solo.rb -j mconf-live-standalone.json
[2019-08-09T04:31:33-07:00] WARN: *****************************************
[2019-08-09T04:31:33-07:00] WARN: Did not find config file: /solo.rb. Using command line options instead.
[2019-08-09T04:31:33-07:00] WARN: *****************************************
[2019-08-09T04:31:33-07:00] WARN: No cookbooks directory found at or above current directory.  Assuming /var/chef.
[2019-08-09T04:31:33-07:00] WARN: *****************************************
[2019-08-09T04:31:33-07:00] WARN: Did not find config file: /solo.rb. Using command line options instead.
[2019-08-09T04:31:33-07:00] WARN: *****************************************
[2019-08-09T04:31:33-07:00] FATAL: Cannot load configuration from mconf-live-standalone.json
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$
admin@mclive:~/downloads/mconf-live-solo-master$ sudo chef-solo -c $PWD/solo.rb -j $PWD/mconf-live-standalone.json
[2019-08-09T04:35:25-07:00] INFO: Started Chef Infra Zero at chefzero://localhost:1 with repository at /home/admin/downloads/mconf-live-solo-master
  One version per cookbook

Starting Chef Infra Client, version 15.2.20
[2019-08-09T04:35:25-07:00] INFO: *** Chef Infra Client 15.2.20 ***
[2019-08-09T04:35:25-07:00] INFO: Platform: x86_64-linux
[2019-08-09T04:35:25-07:00] INFO: Chef-client pid: 20406
[2019-08-09T04:35:32-07:00] INFO: Setting the run_list to ["recipe[bigbluebutton::abort-if-being-used]", "recipe[apt::default]", "recipe[chef_handler::default]", "recipe[mconf-utils::reboot-requestor]", "recipe[reboot-handler]", "recipe[mconf-utils::base]", "recipe[logrotate::default]", "recipe[bigbluebutton]", "recipe[mconf-live]"] from CLI options
[2019-08-09T04:35:32-07:00] INFO: Run List is [recipe[bigbluebutton::abort-if-being-used], recipe[apt::default], recipe[chef_handler::default], recipe[mconf-utils::reboot-requestor], recipe[reboot-handler], recipe[mconf-utils::base], recipe[logrotate::default], recipe[bigbluebutton], recipe[mconf-live]]
[2019-08-09T04:35:32-07:00] INFO: Run List expands to [bigbluebutton::abort-if-being-used, apt::default, chef_handler::default, mconf-utils::reboot-requestor, reboot-handler, mconf-utils::base, logrotate::default, bigbluebutton, mconf-live]
[2019-08-09T04:35:32-07:00] INFO: Starting Chef Infra Client Run for mclive
[2019-08-09T04:35:32-07:00] INFO: Running start handlers
[2019-08-09T04:35:32-07:00] INFO: Start handlers complete.
resolving cookbooks for run list: ["bigbluebutton::abort-if-being-used", "apt::default", "chef_handler::default", "mconf-utils::reboot-requestor", "reboot-handler", "mconf-utils::base", "logrotate::default", "bigbluebutton", "mconf-live"]
[2019-08-09T04:35:33-07:00] INFO: Loading cookbooks [firstname.lastname@example.com, firstname.lastname@example.com, firstname.lastname@example.com, firstname.lastname@example.com, email@example.com, email@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com, email@example.com, email@example.com, firstname.lastname@example.com, email@example.com, email@example.com, email@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com, firstname.lastname@example.com, firstname.lastname@example.com]
Synchronizing Cookbooks:
[2019-08-09T04:35:33-07:00] INFO: Storing updated cookbooks/bigbluebutton/README.md in the cache.
[2019-08-09T04:35:33-07:00] INFO: Storing updated cookbooks/bigbluebutton/templates/default/bigbluebutton.erb in the cache.
[2019-08-09T04:35:33-07:00] INFO: Storing updated cookbooks/bigbluebutton/templates/default/bigbluebutton.nginx.erb in the cache.
[2019-08-09T04:35:33-07:00] INFO: Storing updated cookbooks/bigbluebutton/templates/default/remove-recordings-raw.erb in the cache.
[2019-08-09T04:35:33-07:00] INFO: Storing updated cookbooks/bigbluebutton/recipes/gem-deps.rb in the cache.
[2019-08-09T04:35:33-07:00]

Answer: The issue was raised because with no path it search as /file , The sudo chef-solo -c solo.rb command given just. Gave fully qualified path to the files. I assume being in /vagrant, -c ./solo.rb would work also. I just edit the command as sudo chef-solo -c /vagrant/solo.rb -j /vagrant/node.json and executed nicly


How prove there exists a point $(x_{0},y_{0})$, such $\Delta f|_{(x_{0},y_{0})}\ge 0$

Question: Question:
Assume that the function $f(x,y)$ is twice continuously differentiable on $\mathbb R^2$, and
$$f\big|_{\partial\Sigma}=0,\quad \text{where}\,\,\,\partial\Sigma=\{(x,y)\in\mathbb R^2:x^2+y^2=1\},
$$
and
$$
\lim_{x\to\infty}f(x,0)=1.
$$
Show that there exists a point $(x_{0},y_{0})$, such $\Delta f(x_{0},y_{0})\ge 0$,
where $\Delta$ is Laplace operator. See http://en.wikipedia.org/wiki/Laplace_operator
This problem  is from (problem 8):http://www.doc88.com/p-98539219502.html
My try: since
$$
\Delta f=\dfrac{\partial^2f}{\partial x^2}+\dfrac{\partial^2f}{\partial y^2},
$$
so assume that
$$\Delta f=\dfrac{\partial^2f}{\partial x^2}+\dfrac{\partial^2f}{\partial y^2}<0,\,\forall(x,y)\in \mathbb R^2,$$
then I can't , This problem is hard?
Thank you
Comment: Sorry but this is not a try.
Comment: I agree with Did that yours is not a real try. Why don't you analyze the restriction of $f$ to the $x$-axis, instead? By this I mean the function $\phi(x)=f(x, 0)$. You have a lot of information on $\phi$ and you might discover something interesting.
Comment: @math110 What these informations have to do with anything, I fail to see.
Comment: @mike There is no assumption that the function is bounded below.
Comment: @Did,yes,But this Admission to graduate entrance exam problem,so I think have nice methods,Thank you
Comment: if the laplacian is always <  0 the fctn is superharmonic.  The non-existence of superharmonic fctns bounded below in 2d is standard.
Answer: Despite what the other answer suggests, the assertion is false. There exist functions $f$ in $C^2(\mathbb R^2)$ such that

$\Delta f(x,y)<0$ for all $(x,y)\in\mathbb R^2$,
$f(x,y) = 0$ if $x^2 + y^2 = 1$, and
$\lim_{x\to\infty}f(x,0) = 1$.

Here's how to make one. Pick a smooth function $\eta$ on $\mathbb R$ such that $\eta(x) = 1$ for $x\leq 2$ and $\eta(x) = 0$ for $x\geq 3$. Let $\rho$ be a twice continuously differentiable function on $\mathbb R$ such that $\rho(x)=1$ for $x\leq 1$. (The function $\eta$ will remain unchanged, but I'll determine what else we need to ask of $\rho$ in a moment.) Define
\begin{align*}
f(x,y) & =
1-\eta(x)x^2 - \rho(x)y^2
\end{align*}
First, $f$ is twice continuously differentiable. Second, $f$ satisfies (2) because for $x\leq1$, we have $f(x,y) = 1-x^2 - y^2$. Also, $f$ satisfies (3) because $\eta(x) = 0$ for $x\geq 3$ and so for those $x$ we have $f(x,0) = 1-\eta(x)x^2 = 1$. Finally, for $x\leq 1$, we have $$\Delta(f(x,y)) = \Delta(1-x^2-y^2) = -4 < 0.$$ The question is thus whether we can make $\Delta f<0$ when $x>1$.
For $x>1$
\begin{align*}
\Delta(f(x,y)) & = \Delta(1-\eta(x)x^2 - \rho(x)y^2) \\
& = -\Delta(\eta(x)x^2) - {\partial^2\over \partial x^2}(\rho(x)y^2) - {\partial^2\over \partial y^2}(\rho(x)y^2) \\
& = -\Delta(\eta(x)x^2) - \rho''(x)y^2 - 2\rho(x). \tag{1}
\end{align*}
Now for $1<x\leq 2$, we have $\eta(x) = 1$, so $-\Delta(\eta(x)x^2) = -\Delta(x^2) = -2$. Thus if we can ensure that $\rho''$ and $\rho$ are positive, then $(1)$ will be negative for $x\in(1,2]$.  On the other hand, $\eta$ has compact support in $[2,\infty)$, so $\Delta(\eta(x)x^2)$ does as well. This means in particular that $\Delta(\eta(x)x^2)$ is bounded in $[2,\infty)$, say $|\Delta(\eta(x)x^2)|<M$. Therefore, if we can ensure that
$$
M - \rho''(x)y^2 - 2\rho(x) <0, \tag{2}
$$
then $(1)$ will be negative for all $x\in [2,\infty)$. Actually, if we make sure that $\rho''(x)\geq 0$ for $x>1$, then we need only have $M-2\rho(x)<0$ for $x\geq 2$ to satisfy $(2)$.
In sum, we will be done if we find $\rho\in C^2(\mathbb R)$ such that (i) $\rho(x)=1$ for $x\leq 1$, (ii) $\rho(x)>0$ and $\rho''(x)\geq 0$ for $x\geq 1$, and (iii) $M- 2\rho(x)<0$ for $x\geq 2$. But it's easy to come up with $\rho$ satisfying (i), (ii), and (iii). For example, we could take
\begin{align*}
\rho(x) =
\left\{\begin{array}{ll}
1& x\leq 1, \\
1+M(x-1)^3 & x>1.
\end{array}\right.
\end{align*}
With that, we are done.
Comment: Nice. I think you meant to also state that $\rho(x)=1$ for $x < 1$ though.
Comment: @GeorgeLowther Thanks. Well, I opted to define $f$ piecewise instead of making $\rho(x) = 1$ for $x<1$. But I think I will change it momentarily so that I can just define $f(x,y) = 1-\eta(x)x^2 - \rho(x)y^2$ on all of $\mathbb R^2$ instead of just on the half-plane $x\geq 1$.
Comment: Ok, I changed it.


Mixins in loopback4

Question: I want to add createdAt and updatedAt to each model on loopback 4
can not find name 'MixinTarget'.
Type parameter 'T' of exported function has or is using private name 'MixinTarget'.
If I try from documentation above error occurs.
Comment: can you provide a link to the documentation you're referencing to?
Comment: https://loopback.io/doc/en/lb4/migration-models-mixins.html in this "LoopBack 4 Approach"
Answer: MixinTaget must be imported from @loopback/core:
import {MixinTarget} from '@loopback/core';
import {Class} from '@loopback/repository';

export function TimeStampMixin<T extends MixinTarget<object>>(baseClass: T) {
  return class extends baseClass {
    // add a new property `createdAt`
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    public createdAt: Date;
    constructor(...args: any[]) {
      super(args);
      this.createdAt = new Date();
    }
    printTimeStamp() {
      console.log('Instance created at: ' + this.createdAt);
    }
  };
}

Further reading
As of the writing of this answer, the docs hasn't been updated to reflect the latest clarifications.

https://github.com/strongloop/loopback-next/blob/4932c6c60c25df885b4166b7c4c425eba457a73b/docs/site/Mixin.md
Answer: To resolve this issue, I didn't use the mixin approach. I added the following fields to my model.
  @property({
    type: 'date',
    default: () => new Date(),
    postgresql: {
      columnName: 'updated_at',
    },
  })
  updatedAt?: Date;

It should work as expected
Comment: oh ok thanks for the reply but just wanted to see how mixin works in loopback 4

Mixins in loopback4


TypeScript - Initialise property from another JavaScript file

Question: I am using TypeScript and Firebase together.
My class has fireybase: FirebaseInterface; property.
When I initialise it using this.fireybase = new Firebase('URL/');
I get a compile time error about the Firebase object.
The name 'Firebase' does not exist in the current scope

interface FirebaseInterface {
    set(s:string): any;
}

I have tried adding a Firebase interface into the library but it still doesn't like it.
What is the best approach to doing this in TypeScript?
Comment: I dont know anything about Firebase, but correct me if i am wrong, I see `this.fireybase` in your code. IS there supposed to be a `y` in your "fireybase"?? Just checking to see if this is not a [PEBKAC](http://en.wikipedia.org/wiki/User_error) error.
Comment: Max: a bit more code would be extremely helpful to spotting the issue.
Answer: The typescript compiler tells you that it is unable to find type Firebase so you need to introduce it. In your case, if the providers of the firebase library want to support development in Typescript, they would need to provide a declarations file that specifies the type Firebase (and dependendant types). In your case, a simple Firebase.d.ts file might look as follows:
Firebase.d.ts
declare class Firebase {
    constructor(u:string);
    set(s:string): any;
}

Then you need to bring the declarations file into scope with a reference declaration as follows:
MyApp.ts
///<reference path='firebase.d.ts'/>
class MyApp {
    fireybase: Firebase;
    constructor () => {
        this.fireybase = new Firebase('URL/');
    }
}

You can read more about declaration files and reference paths in the language specification.
Answer: I think you need a reference to a module that contains the Firebase static definitions. Maybe a quick fix would be to use the following statement at the top of the file:
declare var Firebase: any;


Datetime and Timespan Caused Error in Kusto Command

Question: I need to append a row that contains timespan and datetime in kusto command. However,
kusto is throwing error saying

Query schema does not match table schema.
QuerySchema=('string,string,string,string,string'),
TableSchema=('string,string,datetime,datetime,timespan')

Here's my syntax:
.append async Student <| print StudentID = "12345", StudentName = "John", StartTime = datetime(2021-12-06T08:20:02.011052Z), EndTime = datetime(2022-01-06T11:20:02.011052Z), Duration = time(00:00:00.0000509)

Did I miss anything in the syntax here?
Answer: the output schema of the query-part of your command, and the schema of the target table must match in the nubmer of columns, their data types, and their order. column names don't matter.
if, for example, your target table has the following schema: (a:string, b:int, c:dynamic) and you want to append one record with only a and c populated, then you need to provide some value for b as well.
for example:
.append MyTable <| print "hello", int(null), dynamic([1,2])
and not:
.append MyTable <| print "hello", dynamic([1,2])
one way you can figure out the differences in the schema in your
specific case is by running the following queries, and then aligning the differences:
Student | getschema
print StudentID = "12345", StudentName = "John", StartTime = datetime(2021-12-06T08:20:02.011052Z), EndTime = datetime(2022-01-06T11:20:02.011052Z), Duration = time(00:00:00.0000509) | getschema
BTW, the error message you included is likely from a different execution you ran, and not the one you quoted - as this part: QuerySchema=('string,string,string,string,string') doesn't match the fact you have datetime and timespan columns in the quoted command.


How to set up redis to work with SSL on a mac

Question: Could you please help me to set up redis working with SSL on the local computer? I did  once and it worked,
after some time, when I try to connect i ve got this error:
redis-cli --tls --cacert /usr/local/share/ca-certificates/ca.crt
Could not connect to Redis at 127.0.0.1:6379: SSL_connect failed: certificate verify failed

I followed this article https://godfrey-tutu.medium.com/redis-6-deployment-with-tls-authentication-on-centos-7-8b6e34d11cd0
i did this set of commands:
sudo -s  // need to be able to run all next commands

mkdir /tmp/certs && cd /tmp/certs
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -sha256 -key ca.key -days 365 -subj '/O=A/CN=127.0.0.1' -out ca.crt
openssl genrsa -out redis.key 2048
mkdir /etc/ssl/private
openssl req -new -sha256 -nodes -key redis.key -subj '/O=A/CN=127.0.0.1' | openssl x509 -req -sha256 -CA ca.crt -CAkey ca.key -CAserial /etc/ssl/private/ca.txt -CAcreateserial -days 365 -out redis.crt

mkdir /usr/local/share/ca-certificates
cp ca.crt /usr/local/share/ca-certificates/
cp ca.key /etc/ssl/private/
cp redis.key /etc/ssl/private/
cp redis.crt /etc/ssl/

chown andrey /usr/local/share/ca-certificates/ca.crt
chmod 644 /usr/local/share/ca-certificates/ca.crt

chown andrey /etc/ssl/private/ca.key
chmod 400 /etc/ssl/private/ca.key

chown andrey /etc/ssl/private/redis.key
chmod 400 /etc/ssl/private/redis.key

chown andrey /etc/ssl/redis.crt
chmod 644 /etc/ssl/redis.crt

and here my redis config file
port 0
tls-port 6379

# Configure a X.509 certificate and private key to use for authenticating the
# server to connected clients, masters or cluster peers.  These files should be
# PEM formatted.
#

tls-cert-file /etc/ssl/redis.crt
tls-key-file /etc/ssl/private/redis.key

# Configure a DH parameters file to enable Diffie-Hellman (DH) key exchange:
#
# tls-dh-params-file redis.dh

# Configure a CA certificate(s) bundle or directory to authenticate TLS/SSL
# clients and peers.  Redis requires an explicit configuration of at least one
# of these, and will not implicitly use the system wide configuration.
#
tls-ca-cert-file /usr/local/share/ca-certificates/ca.crt
# tls-ca-cert-dir /etc/ssl/certs

# By default, clients (including replica servers) on a TLS port are required
# to authenticate using valid client side certificates.
#
# If "no" is specified, client certificates are not required and not accepted.
# If "optional" is specified, client certificates are accepted and must be
# valid if provided, but are not required.
#
tls-auth-clients no
# tls-auth-clients optional

# By default, a Redis replica does not attempt to establish a TLS connection
# with its master.
#
# Use the following directive to enable TLS on replication links.
#
# tls-replication yes

# By default, the Redis Cluster bus uses a plain TCP connection. To enable
# TLS for the bus protocol, use the following directive:
#
# tls-cluster yes

# Explicitly specify TLS versions to support. Allowed values are case insensitive
# and include "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" (OpenSSL >= 1.1.1) or
# any combination. To enable only TLSv1.2 and TLSv1.3, use:
#
tls-protocols "TLSv1.2 TLSv1.3"

# Configure allowed ciphers.  See the ciphers(1ssl) manpage for more information
# about the syntax of this string.
#
# Note: this configuration applies only to <= TLSv1.2.
#
# tls-ciphers DEFAULT:!MEDIUM

# Configure allowed TLSv1.3 ciphersuites.  See the ciphers(1ssl) manpage for more
# information about the syntax of this string, and specifically for TLSv1.3
# ciphersuites.
#
tls-ciphersuites TLS_CHACHA20_POLY1305_SHA256

# When choosing a cipher, use the server's preference instead of the client
# preference. By default, the server follows the client's preference.
#
tls-prefer-server-ciphers no

# By default, TLS session caching is enabled to allow faster and less expensive
# reconnections by clients that support it. Use the following directive to disable
# caching.
#
# tls-session-caching no

# Change the default number of TLS sessions cached. A zero value sets the cache
# to unlimited size. The default size is 20480.
#
# tls-session-cache-size 5000

# Change the default timeout of cached TLS sessions. The default timeout is 300
# seconds.
#
# tls-session-cache-timeout 60

So this worked fine some days
I try to recreate  certificates again but it does not help
what I am doing wrong?
Comment: The problem was in certificate generation:
openssl req -x509 -new -nodes -sha256 -key ca.key -days 365 -subj '/O=A/CN=127.0.0.1' -out ca.crt
openssl genrsa -out redis.key 2048
mkdir /etc/ssl/private
openssl req -new -sha256 -nodes -key redis.key -subj '/O=A/CN=127.0.0.1' | openssl x509 -req -sha256 -CA ca.crt -CAkey ca.key -CAserial /etc/ssl/private/ca.txt -CAcreateserial -days 365 -out redis.crt
CN should be different
Answer: The problem was in certificate generation:
openssl req -x509 -new -nodes -sha256 -key ca.key -days 365 -subj '/O=A/CN=127.0.0.1' -out ca.crt openssl genrsa -out redis.key 2048
openssl req -new -sha256 -nodes -key redis.key -subj '/O=A/CN=127.0.0.1' | openssl x509 -req -sha256 -CA ca.crt -CAkey ca.key -CAserial /etc/ssl/private/ca.txt -CAcreateserial -days 365 -out redis.crt
CN should be different –


Find the eigenvalues of the linear transformation

Question: I was trying to solve this problem but I got a little stuck in the second point:

Let T be the linear transformation T: $R[x] \rightarrow R[x]$,the polynomials of x with real coefficients, such that:
$T(p(x))=p(3x)$.
a) Show that T is bijective.
b) Find the eigenvalues of T.
c) Prove that does not exit a polynomial $p(x) \in R$ such that: $T^{-1}=p(T)$

It is easy to prove a), but when I tried to prove b) I got some problems, because $R[x]$ is not a finite dimensional space so I can not proceed as I always do finding the matrix of the transformation. So I don't really know how to find the eigenvalues of T when the space does not have a finite basis.
I would really appreciate any hint or advice you could give me.
Thanks.
Comment: Start from the definition of an eigenvalue $T(p(x))=\lambda p(x)$ which gives $p(3x)=\lambda p(x)$. For what $p(x)$ can this be satisfied?
Comment: Recall the meaning of an _eigenvector_ (a vector which is mapped to a constant multiple of itself, under the transformation) and the corresponding _eigenvalue_; does that help?
Comment: Is $R[x]$ the polynomials of $x$ with real coefficients?
Answer: Suppose $\;\lambda\;$ is an eigenvalue with eigenvector $\;h(x)=\sum\limits_{k=0}^n a_kx^k\in\Bbb R[x]\;$ , then
$$h(3x)=T(h(x))=\lambda h(x)\iff \sum_{k=0}^n a_k3^kx^k=\sum_{k=0}^n a_k\lambda x^k\iff$$
$$\iff\,\forall\,k=0,1,...,n\;,\;\;a_k3^k=a_k\lambda\iff\lambda=3^k\;\;\text{for at least one}\;\;k$$
and the only possibility the above is a constant is if $\;k=0\implies \lambda=1\;$. So all the constant polynomials are eigenvectors of $\;T\;$ belonging to the eigenvalue $\;1\;$ .
Comment: I don't think that this is the correct solution. $a_k$ can be non-negative just for one $k$.
Comment: To add on to what @eyedropper said, the condition $a_k 3^k = a_k\lambda \iff \lambda = 3^k$ only holds under the assumption that $a_k\neq 0$.
Comment: Thank you, I really forgot to use the definition of eigenvector, it was not as hard as I was thinking.
Comment: @David My pleasure. Indeed, sometimes the basic definitions are the easiest way to go.
Answer: You should immediately note from $p(3x)=\lambda p(x)$ that $p(x)$ cannot be a polynomial having any $x$ of different degrees. Let $p(x)=ax^k $ with $a\in \mathbb{R}$. Then
$$T(p(x))=ap(3x)=a(3x)^k=a3^kx^k=3^k(ax^k)=3^kp(x)$$
Thus $\lambda = 3^k$. We deduce that $T$ has an infinite number of eigenvectors that come from the set $\{x^k|k\in \mathbb{N}_0\}$ for the eigenvalues $\{3^k|k\in \mathbb{N}_0\}$.
Comment: Thanks, I was checking an as you say for a polynomial $p(x)=a_n x^n + ... + a_0$ I would have that $3^i = \lambda$ and $a_0=\lambda a_0$ so $\lambda=1$. The thing is get confused with the fact that $\lambda = 3^i$ and $\lambda = 1$, but as you say then T will have an infinite number of eigenvalues.
Answer: Nobody has said anything about part c), so here are my two cents:
Hint: Note that the eigenvalues of $T^{-1}$ are $\{3^{-i}\}$ where $i\geq 0$ is an integer.  The eigenvalues of $p(T)$, on the other hand, are $\{p(3^i)\}$ where $i \geq 0$ is an integer.
Note that for any polynomial $p$, we have
$$
\lim_{i \to \infty} |p\left( 3^i\right)| = \infty
$$
but the eigenvalues of $T^{-1}$ form a bounded set.


Simplification of a Finite Sum

Question: For $m, n \in \mathbb{N}$, can  $$\sum_{k=0}^{m} (m-k)! { m \choose m-k } { n \choose n - (m-k) } ( 1 - p)^{k} \cdot p^{m-k} \cdot \frac{ e^{-\lambda} \lambda^{n-(m-k)} } { (n - (m-k) )! }  $$ be simplified?
This is related to a previous question I asked regarding the number of $r$-permutations of a multiset $ S = \{\!\!\{ m \cdot 0, 1, ..., n \}\!\!\}$  [1]. Here, each permutation is weighted by a product of a Bernoulli and a Poisson distribution - I am trying to work out the normalising constant for a joint distribution.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\sum_{k = 0}^{m}\pars{m - k}!{m \choose m - k}{n \choose n - \bracks{m - k}}
\pars{1 - p}^{k}\, p^{m - k}\,{\expo{-\lambda}\lambda^{n - \pars{m -k}}
\over  \bracks{n - \pars{m - k}}!}
\\[5mm] = &\
\sum_{k = 0}^{m}k!{m \choose k}{n \choose n - k}
\pars{1 - p}^{m - k}\, p^{k}\,{\expo{-\lambda}\lambda^{n - k}
\over  \pars{n - k}!}
\\[5mm] = &\
\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}
\sum_{k = 0}^{m}{k! \over \pars{n - k}!}{m \choose k}{n \choose n - k}
\bracks{p \over \pars{1 - p}\lambda}^{k}
\\[5mm] = &\
\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}
\sum_{k = 0}^{m}{m!\, n! \over \pars{n - k}!\pars{m - k}!\pars{n - k}!}
{\bracks{p/\pars{1 - p}\lambda}^{\, k} \over k!}
\\[5mm] = &\
\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}
\sum_{k = 0}^{m}{\bracks{\prod_{i = 1}^{k}\pars{m - i + 1}}
\bracks{\prod_{j = 1}^{k}\pars{n - j + 1}} \over
\prod_{\ell = 1}^{k}\pars{n - \ell}}
{\bracks{p/\pars{1 - p}\lambda}^{\, k} \over k!}
\\[5mm] = &\
\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}
\sum_{k = 0}^{m}{\bracks{\pars{-1}^{k}\prod_{i = 1}^{k}\pars{i - m - 1}}
\bracks{\pars{-1}^{k}\prod_{j = 1}^{k}\pars{j - n - 1}} \over
\pars{-1}^{k}\prod_{\ell = 1}^{k}\pars{\ell - n}}
{\bracks{p/\pars{1 - p}\lambda}^{\, k} \over k!}
\\[5mm] = &\
\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}
\sum_{k = 0}^{m}{\pars{-m}_{k}\pars{-n}_{k} \over \pars{1 - n}_{k}}
{\bracks{-p/\pars{1 - p}\lambda}^{\, k} \over k!}
\\[5mm] = &\
\bbx{\pars{1 - p}^{m}\expo{-\lambda}\lambda^{n}\
\mbox{}_{2}\mrm{F}_{1}\pars{-m,-n;1 - n;-\,{p \over \pars{1 - p}\lambda}}}
\end{align}

See
  The Hypergeometric Series.
Comment: Thank you for the reply. I do not quite understand the simplification made to the Poisson factor in the first line, could you possibly elaborate on it?
Comment: @SCJ I used the following identity: $\displaystyle\sum_{k = a}^{b}c_{k} = \sum_{k = a}^{b}c_{a + b - k}$. Besides that, I move out all the factors which are $\displaystyle k$-independent.
Answer: Not sure that there's a "nice/compact" form available.  Using Mathematica one obtains the following:
<code>Sum[(m - k)! Binomial[m, m - k] Binomial[n, n - m + k] (1 - p)^k p^(m - k)
  Exp[-\[Lambda]] \[Lambda]^(n - m + k)/(n - m + k)!, {k, 0, m}]
</code>
$$\frac{e^{-\lambda } n! p^m \lambda ^{n-m} \, _1F_2\left(-m;-m+n+1,-m+n+1;\frac{(p-1) \lambda }{p}\right)}{((n-m)!)^2}$$
where $\, _1F_2$ is the generalized hypergeometric function (1F2).

Simplification of a Finite Sum


Better way to validate fields using function php

Question: For validation the for given field i written function like this. Please review and improve my function to project worthy
my field
<code>try{
    $message = 'First Name accepts keyboard characters only.';
    doValidateField ( $firstName, 'First Name', true, 100, '/^([a-zA-Z0-9._\- #,^&`~<>:!@$(){}\"\';\*\[\]?%| \n \r \t]*)$/', $message );
} catch ( Exception $e ) {
    $errorMessage = $e->getMessage ();
    echo $errorMessage;
}
</code>
function
<code>/*
* The following function is validates the fields
* @params unknown values $fieldValue, $fieldName, $required, $maxLength, $mask, $message
* @return tables rows $rowResponse
*/

function doValidateField($fieldValue, $fieldName, $required, $maxLength, $mask, $message) {
    // Checking the required field is empty or not
    if ($required) {
        if (strlen ( $fieldValue ) <= 0) {
            throw new Exception ( $fieldName . " is required." );
        }
    }

    // Check field length is not greater than allowed length
    if (strlen ( $fieldValue ) > $maxLength) {
        throw new Exception ( $fieldName . " cannot be greater than " . $maxLength . " characters." );
    }

    // check if specified mask exists in the field
    if (! (preg_match ( $mask, $fieldValue ))) {
        throw new Exception ( $message );
    }

}
</code>
Comment: So Émile, Jörg, Björk, Józef and Ángel are not allowed to enter thier own names?
Comment: Is something not working? Or maybe you're looking for http://codereview.stackexchange.com?
Comment: "better" in which sense? Can you point out which problems you see with the current version?
Comment: You should write more specific functions (smaller, easier functions), like IsEmail(), IsStrLen(). All you need to do then is to "loop" through all your tests and call the according smaller function.
Comment: This is not php validation but javascript
Answer: This is probably a bit less-specific than the answer you want, but I would suggest you take at look at some of the patterns and ideas used by the Zend_Validator classes. (It says "Zend", but it is not a default part of PHP.)
On that note:

I wouldn't throw exceptions. It makes it easier to find the first problem, but harder to loop through multiple validators. Typically you'll want to show people all the places they made an error, rather than showing only the first problem and making them repeatedly submit the form to work their way through them all.
Don't make a validation function, make a validation class. Basically, use OOP. Not only does it make for cleaner and easier-to-improve code, but you can make copies of the validator and tweak their rules/messages slightly as necessary.
Remember that things get a little weird when you start dealing with accented characters or different languages. Figure out whether the thing you are building needs extra work for that or not.


Do all fasteners for a sliding door need to be in framing?

Question: Just purchased a new townhome and for some reason the builder didn't think we needed a door between the master bedroom and bathroom (there is a door for the toilet).
We purchased a sliding barn door to fill in the doorway but there are some issues.  The rail for the door is 6 1/2 feet long with 5 pre drilled holed for attaching. The problem is when lining up the rail, either all 5 attachment goes into a stud but the door doesn't close all the way or I can get 2 attachments into a stud and 1 into 2x4 header but the 2 attachments left of the doorway will be in the drywall.
Will the 3 and 2 be strong enough?  Is it possible to get a longer railing?  Or should I drill a new hole into the rail and have 4 attachments into wood?
Comment: Can you post some pictures of the railing?   I might take a chance using drywall if one hole was in the centre of the railing, but I would prefer all screws in solid wood, studs or using a piece of wood screwed into the studs that I can hang/screw the railing on.  I am assuming you brought the house already built so the missing door is a design statement instead of a mistake/building error.
Answer: I would consider drilling extra holes to get screws into studs. Otherwise, you may have to bury "stretcher" wood between studs behind the drywall to allow for the factory holes to be used.
Comment: Yes, you risk sag (which can be _horizontal_) without fasteners at adequately close intervals.
Answer: Answering my own question...
I just noticed this barn door kit comes with dry wall anchors so I guess they think they drywall can hold the door with anchors.  I will be doing 3 bolts in wood and 2 in drywall with anchors.
Comment: Good idea, wall anchors wont be enough.