What does CPython do when we access an element of the list by index?

Question: Can you please explain the process that is performed on the background when we access an element of the list by index?
My knowledge of C is pretty limited, thus I cannot fully understand the source code. So far I have identified this function declaration as the relevant one.
Based on this article, my understanding is that a list is an array of pointers. Once the list is created, the list structure contains the length and the allocated memory which is normally greater than size. However, I do not understand the following:
When we access an element, do we make use of length of the list? Or we just access the pointer ob_item[i]?
The following question does not answer this one as it only covers list implementation.
Comment: Besides the list range checks, all the essential logic is in the line `return ((PyListObject *)op) -> ob_item[i];`, and `ob_item` is explained in the linked question.
Comment: Does it mean that in order to return an element we need to know the length of the array to perform those range checks?
Comment: The size of the list is certainly stored within the interpreter since `__len__` is possible.
Comment: I have edited the question to make it a bit more concrete. I do not understand the following: whether when we access an element, do we make use of the length of the list?
Answer: Python uses the length of the list you're indexing to check if the index is out of range. It doesn't need the length for the actual indexing step, but C doesn't have any protection against indexing beyond the end of an array, so checking the length first is important.
It's worth noting that the function you linked is not the function that implements indexing from Python code. Rather, it is a C API function that is mostly intended for other C code to use. The function that actually gets called when you index a list from Python code is called list_subscript which you can see further down the source code. That function handles negative indexes (and slices) and then calls another function to do the actual indexing. For integer indexes, it calls list_item, which is almost the same as the more generic PyList_GetItem you were looking at (PyList_GetItem includes a check that confirms the object it's being called on is actually a list).
Comment: Thank you for this answer. This makes total sense to me. Does the same stand for reverse indexing? In the list_subscript I can see that if i is negative, then  PyList_GET_SIZE(self) is called. Would that imply that for the reverse indexing we need the size ?
Comment: Based on the lines 2929 and 2930 in the source code you provided, the way it is handled is we add the length of the array to the negative index to retrieve the element. Correct me if I am wrong.
Comment: Yes, that's right. For negative indexes you really do need the size of the list to get the right index, not only for bounds checking.
Answer: C doesn't check if the index and I assume CPython neither. This means that when you try to access an element in a list, it will be assumed the index is not out of bounds. This means it's up to the programmer to perform those checks using the length of the list. In the code you provide, there is a function valid_index(...) that does this.
Comment: Yes, Py_SIZE(p) returns the size of an object. So in this case the length of the list is used upon element access to perform a bounds check (as good practice dictates).
Comment: According to the source code, I believe this (https://github.com/python/cpython/blob/0aa0bd056349f73de9577ccc38560c1d01864d51/Objects/listobject.c#L235-L242) performs the checks for us. Hence, the question: is Py_SIZE(p) essentially the length of the array? Which would imply that the length is used upon element access.


Connecting several threaded plumbing components together

Question: I have a string of brass components I need to connect together.
They all have corresponding Male/Female threads, so they all will go together, but is this a good idea?
It occurs to me that it will be difficult/impossible to tighten any of the fittings later without taking the whole lot to pieces?
Is there a 'typical' solution to this?
Comment: Pretty much a duplicate. https://diy.stackexchange.com/q/221755/18078
Answer: Usually one does it right the first time, so there is no need to retighten the whole assembly. Since it is metal, you can use hemp and paste. Hemp swells on contact with water, so it forgives small flaws and tightens well.
To facilitate an eventual future removal, you could put an pipe union fitting on each end of the assembly.
Comment: Always best to get it right first time! I looked at the unions but for 1 1/4" they are about €40, which would make it cheaper put some copper in the middle and use some compression fittings.
Answer: So you put a joint or 2 in place so that it can come apart.
Similar to:

Form: https://www.hornbach.ch/fr/p/raccord-visse-a-joint-conique-en-fonte-malleable-georg-fischer-gf-n340-3-8-fi/10555916/


Serialize alread-built instance of a WinForms.Form to VB or C# Sourcecode, just like the IDE does

Question: I have about 500 WinForms that are generated dynamically from XML files by an old app. I would like to automatically convert these to VB or C# code I can edit in the designer.
I can do it by hand, which would take forever...
Or write an app that loads each XML, calls the old app's xml-to-winform-builder to convert it to a completed WinForm, and examine every control's property and use StringBuilder to generate code that the designer will swallow. Which would be arduous at best.
BUT: I would like to use the same code that the designer uses. This I think will save me time with corner cases.
What I would like to do is, take an already built WinForm object, with control arrays full of child controls (created by the old apps xml-to-winform code), throw it at the same code the IDE uses to serialize the designed form to CodeDom, and get back a CodeDom list of statements I can save in a real language. Once I get the CodeDOM I'll be happy!
EDIT
This Codeproject article embodies the 'concept' of what I want to do: Start with a completed form, convert it ('serialize it') as code. However, it has two lacks: (1) it generates the .aspx page using templates/stringbuilder, and that is where the properties are (fine for webforms, but winforms serializes the properties into the actual .Designer.vb file); (2) it does this all from the ground up. I want to re-use visual studio's routines. They let you do this with many things, for example, the property grid. I'm just seeking a link to an article (maybe my google-fu was too weak), or, a short code sample from something somebody has already done.
Comment: Just to make sure I've got this right: You have a ton of Forms defined using XML, you have code that will convert this XML into a WinForms object.  Now you want to take this process which can automatically generate WinForms using XML templates and make it all hard coded, but with Designer support?  What are you hoping to gain by having designer support?  Are you planning on dropping the xml templating solution?
Comment: @Tommy - Current system can process the XML files, however editing is a pain. Have to do it by hand. Like making an HTML form in notepad. Want to convert to code so I can use the IDE's winforms editor and drag and drop (coming into the 90s here).
Comment: @Peter - 'What am I hoping to gain' - the ability to edit the form design with the IDE's WinForms designer. Right now it's like making HTML forms with notepad. This way, I don't have to write an editor for the properietary format. Converting to HTML and using an HTML editor would allow for changing the visuals but not databinding, etc. that is WinForms extra. I have a converter already to write new screens I'm designing out to XML.
Comment: Why the extra step ? Why not go xml to c#/vb directly ?
Comment: The IDE in question is Visual Studio and most of the code that implements the designers is either native (not reusable at all), or .NET but implemented in private assemblies or private/internal classes.
Comment: Microsoft have a post-VS2012 project called "Roslyn" which exposes the compiler. Not sure if it is relevant: http://www.microsoft.com/en-us/download/details.aspx?id=27746#additional-information
Comment: @SimonMourier, That's unfortunately what I'm suspecting; hence the bounty! If we're right about that, it would be a real shame.
Comment: @sss: Thanks, that sounds cool. But Roslyn takes code and gives you information about it; What I want is to start with a bunch of information, and get code generated from it.
Answer: So this may or may not fit your needs.  I have a solution but it will require that you tweak your XML -> WinForms rendering.
This relies heavily on the use of this project: http://ivanz.com/files/docs/designerhosting/create-and-host-custom-designers-dot-net.html
Download the EXE (which is just a compressed version of the source with a EULA) and build the solution, I had some issues with building until I removed references to the graphing library (and the associated calls to it from the Host library).  Why the Host library needs to draw graphs I'm not really sure...
Then I built a new WinForms project (can't be console because the DesignSurface fails to hook into drag/drop event).  Reference the Host and Loader projects from the above project in your new winforms project.
Here is where you will undoubtably need to tweak your existing process.  Merge your existing process so that it fits into this type of form building shown for my label below:
<code>        HostSurfaceManager hsm = new HostSurfaceManager();
        HostControl hc = hsm.GetNewHost(typeof(Form), LoaderType.CodeDomDesignerLoader);

        var l = new Label() { Text = "TEST!!!!" };

        hc.DesignerHost.Container.Add(l);

        richTextBox1.Text = ((CodeDomHostLoader)hc.HostSurface.Loader).GetCode("C#");
</code>
This generates your form.cs file content (see generated code below).  This is an all in one file, you do not need to create a seperate form.cs.designer file to get designer support.  I copied the code generated above, saved it to a .cs file, and visual studio recognized it as a winform and gave me design support.
Your copy will probably include a sub Main.  I went into the Loader -> CodeGen.cs file and commented out the section related to Main, I would suggest you do the same.
<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.5448
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DesignerHostSample
{
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    public class Form1 : System.Windows.Forms.Form
    {

        private System.Windows.Forms.Label label1;

        public Form1()
        {
            this.InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(0, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(100, 23);
            this.label1.TabIndex = 0;
            this.label1.Text = "TEST!!!!";
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Name = "Form1";
            this.ResumeLayout(false);
        }
    }
}
</code>
edit by FastAl
Peter, you rock!!! This is pretty much exactly what I wanted. Well, I can't exactly just throw the object at it yet; using just the above method, none of the .Controls properties were filled, so I got a blank form. Also it seems like the form has to be created by GetNewHost. Fortunately my XMl-to-screen routine doesn't actually create the container, it just returns a flat list of controls that I must properly reparent (SetChildren sub). Note the comment where I have to add them to the host container for it to know about them. NOW it works perfectly!
<code>Public Module Main
    Public Sub Main()
        Dim FormSpecAsText As String = ...  read XML form def from file
        Dim Outfile As String = ... output file is in my project

        ' Setup for Winforms platform
        Dim dsg As New DynamicScreenGenerator
        Dim ListOfControls As New PanelObjectList
        ControlFactoryLocator.AddService( _
            New PanelObjectFactoryWinFormBasicControls)
        ControlFactoryLocator.AddService(_
            New PanelObjectFactoryWinFormAppSpecificCtls)
        ControlFactoryLocator.AddService(_
            New PanelObjectFactoryWinFormFormEditorCtls)

        ' Deserialize FormSpecAsText into a flat list of Controls
        ListOfControls.AddRange( _
            dsg.BuildDSGLists(FormSpecAsText, ListOfControls).ToArray)

        ' setup for serialization to Code
        Dim hsm As New Host.HostSurfaceManager
        Dim hc As Host.HostControl = _
          hsm.GetNewHost(GetType(Form), Host.LoaderType.CodeDomDesignerLoader)

        ' Get main form that was created via GetNewHost, autosize it
        Dim HostUserControl = _
            CType(hc.DesignerHost.Container.Components(0), Form)

        ' Parent them properly, and add to host (top lvl ctls have parent="")
        SetChildren(HostUserControl, "", dsg, hc.DesignerHost.Container)
        HostUserControl.AutoSize = True

        ' write serialized version to a file in my project
        IO.File.WriteAllText(Outfile, _
          CType(hc.HostSurface.Loader, Loader.CodeDomHostLoader).GetCode("VB"))
    End Sub

    Sub SetChildren(ByVal Parent As Control, ByVal ParentName As String, _
           ByVal dsg As DynamicScreenGenerator, ByVal ctr As IContainer)
        For Each PO In (From p In dsg.POList Where p.Parent = ParentName)
            Dim child = CType(dsg.CTLList(PO), Control)
            ctr.Add(child, PO.Name) ' seem to have to add to container while
             '  parenting them or .Controls isn't serialized and form is blank.
            Parent.Controls.Add(child)
            SetChildren(child, PO.Name, dsg, ctr)
        Next
    End Sub
End Module
</code>
Comment: @FastAI - Glad I could help you get it going. I didn't have any way to really get the kinks worked out since I wrote this just for you, so thanks for posting your revision.


Different response encoding REST using JAVA between my localhost and My Server

Question: I'm trying to get a xml from a REST connection. In my local machine i receive it with the right encoding. e.g.: 수정완료 but in my server I receive the same request as 수정완료.
Using the web browser in both machines I receive the REST request correctly.
Any ideas?
I'm using Apache Tomcat 6.0 in both machines
EDITED:
I'm follow this example:
http://support.openview.hp.com/selfsolve/document/KM997956/binary/ALM11.00_REST_API.html?searchIdentifier=-765a98c0%3a12de84ca170%3a-27ac&resultType=document
user: exampleStack
pass: example

Direct source link: http://h30499.www3.hp.com/hpeb/attachments/hpeb/itrc-895/68767/1/alm_rest.zip
Thanks in advance.
Comment: Please show some code - and tell us you you're displaying the data. I suspect somewhere you're using the platform default encoding...
Comment: HP-Passport required on the link.
Answer: I finally got the answer to solve this issue thanks to this post: https://forums.adobe.com/message/3602618
What I needed to do was instead get directly the string from the Rest response, get its bite[] and then encode it correctly: =)
String myXmlEncoded = new String(con.httpGet().getResponseData(), "UTF-8");

Thanks guys.


Angular2: how to use router-deprecated with ngModule

Question: I switched from rc4 to rc5 and bootstrap to a module, main.ts:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { PortmanModule } from './portman.module';

platformBrowserDynamic().bootstrapModule(PortmanModule);

portman.module:
import {NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {FormsModule} from "@angular/forms";
import {RootComponent} from "./root.component";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule
    ],
    declarations: [RootComponent],
    bootstrap: [RootComponent]
})
export class PortmanModule {
}

Now when I load my app it yields an error:
ORIGINAL EXCEPTION: No provider for Router!
main.ts without ngModule, old rc4 syntax works:
import {bootstrap}    from '@angular/platform-browser-dynamic';
import { disableDeprecatedForms, provideForms } from '@angular/forms';
import {RootComponent} from './root.component'
import {ROUTER_PROVIDERS} from "@angular/router-deprecated";

bootstrap (RootComponent,[
    ROUTER_PROVIDERS,
    disableDeprecatedForms(),
    provideForms()
]).catch((err: any) => console.error(err));

How do I provide the Router?
Answer: I don't know if it's possible to use Router-deprecated with NgModule, but in any case you need to import the reference of the router in your @NgModule imports like this :
app.modules.ts
...
import { appRouting } from './app.routes';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        appRouting, // Routing logic
        LoginModule // Another module
    ],
    ...
})
export class AppModule { }

app.routes.ts
const appRoutes: Routes = [

];

export const appRouting = RouterModule.forRoot(appRoutes);

My best guess would be they also updated router-deprecated to be used with NgModule, but you should check-out the router-deprecated documentation.
Also, my app.routes.ts file is empty because my routing logic is located in the login.routes.ts with the LoginModule, so this is normal.
Comment: I don't know, I switched to the new router
Comment: Please don't forget to let us know if your problem was solved :)
Comment: That would be the best thing to do because things are going to evolve more.


Calling a function of another translation unit can cause static initialization order fiasco

Question: a.cpp
static Foo fooobj;
void Usefoo()
{
    foooobj.somefunc();
}

b.cpp
static Bar barobj;

and here is the constructor of Bar
 Bar::Bar()
 {
     Usefoo();
 }

Will this lead to static initialization order fiasco?
If yes, how can I solve it. I thought of something like below:
Foo* GetFoo*()
{
    static Foo *fooobj = new Foo();
    return fooobj;
}

But since I don't have support of C++11, static local initialization is not thread safe.
Hence this cannot work.
Also what if barobj was non-static. Then I don't have to worry about this fiasco right? For a non-static object initialization which is depending on another non-static object initialization in a different translation unit is not an issue. Right?
Comment: Off-topic: `Foo& getFoo() { static Foo instance; return instance; }` usually is superior singleton pattern, as it would assure that Foo's destructor is called when programme terminates (if you insist on pointer as return value, `Foo* getFoo() { static Foo instance; return &instance }` is fine as well...
Comment: Here you can read how to implement singletons thread safe
https://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-6-double-checked-locking.html
Comment: `Bar& getBar(); Foo& getFoo(); int main() { getFoo(); getBar(); std::thread t1(...); std::thread t2(...); /* ... */ return 0; }` and you shouldn't have problems any more. Actually, as getBar would use getFoo anyway, you wouldn't even have to call the latter, still I'd do for consistency.
Comment: GCC offers an attribute [`init_priority`](https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html) with which you could control initialisation order as well. Be aware, though, that this is a *non-portable* solution!!!
Comment: Does `Bar` depend of `Foo`?
Comment: @Jarod42 No. But `Bar`'s constructor calls `Usefoo()` which internally uses global `fooobj`. My concern is can I be sure that `fooobj` will be completely initialized when I enter `UseFoo`.
Comment: Wait a minute, do you intend to call `GetFoo` with multiple threads unsynchronized? Why do the classes have to be static?
Comment: Do you rely on thread safety at all?
Comment: If you have multiple threads, a pretty simple way to get the singletons initialised correctly would be simply calling the getters once in correct order *before* creating multiple threads, e. g. in `main`.
Comment: @Superlokkus Yes. That is why I cannot use `GetFoo()` to solve this problem.
Comment: @Aconcagua But I cannot guarantee thread safety of `FetGoo()` and static initialization for local variables is not thread safe.
Comment: @user3819404 That's why that comment was prefaced with "off-topic". (But I initially missed that too.)
Comment: @Aconcagua Ooooh TIL
Answer:
Will this lead to static initialization order fiasco?

Yes.

I thought of something like below:

Usually you'd avoid the pointers and do a nice:
Foo& GetFoo()
{
    static Foo fooobj;
    return fooobj;
}

But since I don't have support of C++11, static local initialization is not thread safe.

Okay, still problematic then.

Also what if barobj was non-static. Then I don't have to worry about this fiasco right?

Right. You should avoid these globals. In fact, this is a pretty good example of why we try to avoid globals.
Encapsulate your state into a nice class, perhaps instantiated in main and passed around as needed, instead.

For a non-static object initialization which is depending on another non-static object initialization in a different translation unit is not an issue. Right?

Right. I can't think of a way to break that unless your program has undefined behaviour.
Comment: @Aconcagua There is a third ;)
Comment: For the last part, If there is a global non-static `Bar obj` in `bar.cpp` depending on a global non-static `Foo obj` in `foo.cpp` it should not cause any problems?
Comment: @user3819404 Sorry, not sure what you mean by "global non-static". All globals have static storage duration. The `static` keyword there means "internal linkage". Yes, it's dumb :)
Comment: So my objects are global. So I have a problem. Right?
Comment: @user3819404 Exactly. Just removing the `static` keyword from the variable doesn't change anything about the issue. Confusion arises because one and the same word ('static') is used with two different (context-dependent) meanings...
Comment: @user3819404 Right.
Comment: I understand that the requirements are rigid, but is it possible to have a solution for this scenario taking all the constraints into consideration(like non C++11 support and global variables)>
Comment: @user3819404 I've already answered the question; asking it again won't change the answer. :)


Expression Equals

Question: So, I'm trying to figure out Expression trees. I'm trying to add in a dynamic equals to a Queryable where T is one of several different tables. I'm first checking the table contains the field I want to filter on.
ParameterExpression param = Expression.Parameter(typeof(TSource), "x");

Expression conversionExpression = Expression.Convert(Expression.Property(param, _sourceProperty), typeof(TList));

Expression<Func<TSource, TList>> propertyExpression = Expression.Lambda<Func<TSource, TList>>(conversionExpression, param);

Expression<Func<TList, TList, bool>> methodExpression = (x, y) => x.Equals(y);

ReadOnlyCollection<ParameterExpression> parameters = propertyExpression.Parameters;

InvocationExpression getFieldPropertyExpression = Expression.Invoke(
                                                propertyExpression,
                                                parameters.Cast<Expression>());

MethodCallExpression methodBody = methodExpression.Body as MethodCallExpression;
MethodCallExpression methodCall = Expression.Call(methodBody.Method, Expression.Constant(equalTo), getFieldPropertyExpression);

Expression<Func<TSource, bool>> equalsStatement = Expression.Lambda<Func<TSource, bool>>(methodCall, parameters);

return source.Where(equalsStatement);

When I execute this, I get an issue with the MethodInfo in the Call statement. It tells me;
Static method requires null instance, non-static method requires non-null instance.
I'm no master of Expression trees, but I think I understand about 75% of what I'm doing here and know what I'm trying to achieve. The TList is a bad name right now, but I took this from an example that works to produce an In statement just fine.
I'm really looking for an explanation here so I can work through the code myself, or a solution with an explanation of what I was missing.
Edit:
Ok, so after a very frustrating afternoon and still not quite feeling like I understand what I'm looking at entirely, I think I have an answer.
ParameterExpression sourceObject = Expression.Parameter(typeof(TSource), "x");

Expression<Func<TSource, bool>> check = Expression.Lambda<Func<TSource, bool>>
        (
            Expression.Equal(
            Expression.MakeMemberAccess(sourceObject, typeof(TSource).GetProperty(_sourceProperty)),
            Expression.Constant(equalTo)
        ),
        sourceObject
);

return source.Where(check);

Is anybody able to explain to me why the original just wasn't fit for what I was trying to do? I want to understand more about the actual process, but I feel I'm not picking it up as fast as I would like.
Answer: Expression.Call has two sets of overloads (with lots of overloads in each).  One set is for instance methods and the other set is for static methods.  In those for static methods, the first argument is a MethodInfo object -- exactly like you have.  For instance methods, the first argument should be an Expression representing the target (i.e. the left-hand-side of the "." in a method call.)   Given the error you are receiving, it sounds like the MethodInfo represents a non-static method, and therefore you must provide an expression representing the instance as the first argument.
Comment: Thanks for the response. I marked this as the answer because it made me look at the problem the way I should have been looking at it.

Expression Equals


No scrollbars for scrollable controls on iPad & iPhone

Question: When an element contains overflowing content, there is nothing that tells the user they can scroll to see more. They have to know to try the 2 finger swipe to see if anything moves.
http://support.apple.com/kb/ht1484
Shouldn't there be something to tell the user that there's more to see? I don't feel making them try to swipe to see what happens is acceptable. Can someone make an argument for this behavior?
Comment: Don't they just have to use the one finger swipe to scroll as normal? And technically this is a convention, though I still think it's an important question to ask.
Comment: @Rarity: it was a two-finger swipe until iOS 5 (so not switched to one-finger until very recently).
Comment: @KitGrose ohh...sounds annoying as heck. My first device was iOS5 so I guess I'm spoiled. My touchpad does the two finger thing and I hate it...it's not as sensitive as a good touchscreen however.
Answer: I find that in many applications where I scan scroll on my iPhone, there is a subtle but effective way to telling me that visible: the last line in the scrollable area is only half visible. That quite effectively communicates that there is more to see, and once you start scrolling, you'll  notice that there is an indication where you are in the list.
I know that this does not apply for all scrollable contents. For instance, on a webpage, you cannot control if a line on the bottom will end up in the right position to be only half-visible. However, I get the distinct impression (just playing around with my phone to see what happens now) that here another technique is used: the scrollbars that are visible during scrolling, are also briefly visible when the content is first rendered in the scrollable area. I guess that also serves as a reminder that the content is scrollable. At least Safari uses this technique.
Answer: There is, IMO, nothing about the way that iOS handles scrollable content that is ideal or could be argued to be better than the traditional desktop experience of an always-visible scrollbar.
Importantly, though, this implementation is a very good trade-off for small-sized screens, since persistent scrollbars would take up a very large proportion of the total screen space, especially while the website was completely zoomed out (as it is when desktop websites are first loaded on an iOS device.
Answer: I have found that over the last few years, websites containing "frame" like appearance and feel have begun to die off.
In fact when developing sites I try never to have to use overflow hidden, unless expressly needed for a particular set of functionality; like a scroller/carousel.
For this example I would have used a responsive design that simply makes the containers fit the height and width that best fits the content and the device resolution.


C# Casting with conversion operators

Question: I have a custom implementation of the string class. I added custom conversion operators between string and the class, and the casting is working normally. But, if I first cast the custom object to System.Object and then to string it says: "Unable to cast the type 'MyString' to type 'System.String'". Why is that? How can I enable it...
class MyString
{
    public string S {get; set;}

    public MyString(string s)
    {
        this.S = s;
    }

    public static implicit operator string(MyString s)
    {
        return s.S;
    }
    public static implicit operator MyString(string s)
    {
        return new MyString(s);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyString ms = new MyString("a");
        string s = ms;
        object o = ms;
        string s1 = (string)o; // <-- this throws the exception!
    }
}

Comment: that is an explicit cast.  you dont have an explicit operator
Comment: explicit casts work if implicit cast is defined.
Answer: Conversions like this have to be determined at compile-time - whereas in your final line, the compile-time type of o is just object, so the compiler doesn't "know" about your conversion as an option.
It's hard to know the best solution to your problem other than just saying "don't do that" - if you use dynamic instead of object (and you're using C# 4, of course) then it'll work - but personally I would just try not to rely on user-defined conversions like this. They make the codebase very hard to understand, IMO.
Anyone reading an expression (string) o where o is just object would expect it to be a simple cast, i.e. one which would fail if o didn't actually refer to a string (or was a null reference). Trying to find ways of confounding that expectation is a bad idea, IMO.
Answer: I'd override ToString in your class. And then use o.ToString() instead of (string)o.

C# Casting with conversion operators


Regex to validate logical && || operators in string

Question: I am trying to create a Regex expression to validate logical && || string combonation and its corresponding  opening and closing () brackets.
I have been messing with the Regex hieroglyphic pattern but can't seem to get it working correctly, mainly due to my complete lack of understanding of the Regex pattern.
After several hours of StackOverflow and google this is what I have so far, I feel I am close.
    private void ValidationTest()
    {
        string hieroglyphics = @"^(?=^[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$)[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$";

        var tests = new List<string>
        {
            // Working
             "(1 && 2)",
             "((1 && 2) && (3 || 4))",
             "((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))",

            // Not working
            "(Stack && Overflow)"
        };

        if (tests.All(test => Regex.IsMatch(test, hieroglyphics)))
        {
            MessageBox.Show("Woohoo!!");
        }
    }

So the main issue with what I have so far is if ther are no brackets 1 && 2 it wont validate, same with (1 && 2) && (3 || 4).
Also it seems to ignore words alltogeter (Stack && Overflow)
Examples of some strings I am tring to validate.
"IsRecording && IsPlaying"
"IsVisible && (IsPlaying && (IsMusic || IsRadio))"

There is also some keywords that contain brakets that could mess things up
Example:
"IsWindowVisible(2) && (IsControlVisible(22) && IsControlFocused(100))"

Edit:
As it is now this expression works fine validating the kind of complexity I need, however the only real issue I have is that its nubers only.
Complex example that validates fine with this Regex
"((1 && 2) && (3 || 4) || ((1 && 2) && (3 || 4)))"

A simple string 1 && 2 wont validate without brakets, but I dont mind adding brackest to these.
all I need is to add support for words instead of just numbers, this will be a fixed list of words if that helps.
If someone can spot the error or point me in a better direction would be awesome
Thanks
Edit:
Answer by mellamokb worked perfect. It seems the trouble was the d+ needed to be 0-9a-zA-Z()
Here is the pattern incase it usefull for anyone else.
   string hieroglyphics = @"^(?=^[^()]*(?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))[^()]*$)[(]*[0-9a-zA-Z()]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z()]+[)]*)*$";

it validates exactly what I need
Examples:
 "IsPlayer(Video) && Player(Playing)",
 "((IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34))) || (IsPlayer(Video) && (Player(Playing) && ControlIsVisible(34)))) && ControlIsFocused(22)"

Comment: The "regular" in "regular expression" refers to the restricted class of languages that a regex can accept, the simplest (not totally inaccurate) description of which is that they correspond to a finite state machine that can not count. So it is impossible in true regexp languages to match brackets to arbitrary depth.
Comment: This problem cannot be solved with regular expressions, unless your input string is limited to a fixed number of nested bracket depth. You cannot do it with regex if you want to support indefinite number of nested parentheses. For this you need to write a small custom parser.
Comment: I agree with @SinaIravanian, this is not a problem that a regex can solve. Look into writing a parser and/or grammar. I've actually done something very similar for this same problem and it worked out nicely.
Comment: The sting is compiled in another application using `CodeDom` at the moment I am using the same `CodeDom` method to validate, as you could imagine its pretty slow/stupid, I was just hoping for a simple `Regex` solution, I dont mind setting a depth limit on the nested brakets if it would be possible to use `Regex` or does the amount of nested braket pairs have to be the same for every string?
Comment: What about balancing group definitions? http://msdn.microsoft.com/en-us/library/bs2twtah.aspx#balancing_group_definition
Comment: @David That description is actually pretty accurate (well, the consequence is). What's your gripe with it? That it implies counting to infinity? (Not that this strictly matters here, .NET "regex" *can* count.)
Comment: @Beaner, as it is my regex works it just won't accept letters only numbers, I can live with adding the extra bracket needed around simple expressions `1 && 2` as the `CodeDom` compiler wont care. but its just the number only thing I am stuck with.
Comment: What's the end goal here? Is it to parse an expression from a string and apply it to an object instance?
Comment: @Russ Cam, I have a custom skinnable GUI solution, and It has a skin editor application, the skin editor can build a "VisibleCondition" for a control, This string is complied at startup of the GUI application, I just wanted to add some sort validation as some users may struggle with the `&&` `||` '()' combonation. all I need is words to be accepted in the regex
Comment: @David Carlisle, you said `it is impossible in true regexp languages to match brackets to arbitrary depth` but I can't seem to make this fail, at what point wont this work, My `RegEx` seems to handle any number of nested `()` that I give, I even made a few strings with 30+ nested `()` and it still works fine.
Comment: @sa_ddam213: He is right that strict regular language cannot describe bracket matching. But you are also right since C# regular expression (it is NOT strictly regular) supports bracket matching construct.
Answer: I think the reason you are not able to validate expressions without a wrapping () is the wrapping parentheses in your core nesting logic.  If you take out the following parentheses I note below, then the other two non-wrapped expressions validate:
^(?=^[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\)[^()]*$...
           ^^ remove this                            remove this ^^

Then in order to allow expressions that are not just numerical, you need to replace your restrictive \d with a more liberal definition of what you want to validate, say, [0-9a-zA-Z]:
...[(]*\d+[)]*(\s+(&&|\|\|)\s+[(]*\d+[)]*)*$
       ^^ change these expression ^^

So it would become:
...[(]*[0-9a-zA-Z]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z]+[)]*)*$

Demo: http://ideone.com/jwkcpL


Home Security Camera that is easy to turn off

Question: I live in an apartment and want to install security cameras. However, I want the cameras to be activated (ON) only when no one is at the home (or when I want it to be ON). I do not want it to monitor (and possibly broadcast) me.
I am sure this is a feature lot of other people would be interested in and the cameras might be providing this. I just do not know what to search for? Or what is this feature called?
Comment: Unfortunately, "shopping" questions are off-topic here. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: I tried the Momentum camera and turning the power on-off. But turning that camera back on is very finicky. Sometimes it gets ON, sometime it just gets stuck.
Comment: It's called closed-circuit television.  but if you avoid anything that mentions "cloud" you should be fairly safe.  getting them to record may require more effort though.  this is probably a better question for superuser
Answer: There are likely cameras that have such a feature. But a simple solution is:

Use wired cameras, not WiFi
Connect all the cameras to one network switch. If you are using PoE then you are likely to do that anyway, unless you have other PoE devices such as VOIP phones.
Turn the "camera network switch" off/on as needed.

If the cameras have no substantial memory of their own, then you could actually leave the network switch "on" but disconnect it from the rest of the network. That would avoid any power-cycle issues as the cameras would not lose power, while still preventing broadcast to a recorder (whether local or in the cloud).
Answer: If you trust Amazon's security/privacy features, their CloudCams have a "geofence" feature that works in conjunction with the location service on your smartphone - it will turn the cams on when you're away from home, and off when you're back home. From their FAQ:

You can also set up Home/Away, a geo-fencing feature that automatically turns off Cloud Cam when your phone is in the same location and on again when it's not

They also have a scheduling feature that lets you schedule when the camera is active.
Note that this is not a "hard" off switch, so you're really relying on their software to do what it says. The only way to be sure would be to cut the power to the cameras.
Answer: Or easier yet... Here's something that I've installed for a couple of my customers. You've probably seen the commercials for these. They are called "Ring". It's a doorbell with a camera in it. You connect it to your smart phone I don't remember if the door bell camera is activated by motion or just when someone rings the doorbell. It comes with an extra motion activated camera also. So if someone rings your doorbell (once again I'm not sure if the doorbell camera is motion also) or activates either motion the cameras will turn on and immediately notify you. You will be able to see them and talk to them through your phone. They have no idea if you're home or 1,000 miles away. I've rung the doorbell and was immediately greeted by my customer who was in San Diego. I live in Tucson. I think that it's around $200.00 for the doorbell/camera and a second camera. Super easy to set up and less than an hour to set up.
Comment: Ring is motion sensitive. This is where Youtube videos of package thieves come from.


Give a function $f(x)$ sucht that the given power series is the Taylor series of $f(x)$.

Question: I always have trouble with this question:
Give a function $f(x)$ sucht that the given power series is the Taylor series of $f(x)$.
For example $\sum_{n=1}^{\infty} ((n+\frac{1}{n})x^n)$, or $\sum_{n=0}^{\infty} (\frac{1}{n+1}x^n)$.
Is there a standard way to determine $f(x)$?Or standard steps you can try to find $f(x)$?
Thanks in advance!
Comment: For the first one, do you mean $\sum_n (n+\frac1n)x^n$? Otherwise it's not even a power series.
Comment: @HenningMakholm Yeah I did, sorry just forgot the ()
Comment: Look for "generating function"
Answer: First of all, an universal answer to the problem of knowing a function such that its Taylor series is $\sum_{n=0}^\infty a_nx^n$ (assuming that the radius of convergence $R$ of the series is not $0$) is $f(x)=\sum_{n=0}^\infty a_nx^n$ ($|x|<R$).
But there are tricks to find better answers. For instance, in the case of the series $\sum_{n=1}^\infty\left(n+\frac1n\right)x^n$, you can break it in two: $\sum_{n=1}^\infty nx^n$ and $\sum_{n=1}^\infty\frac{x^n}n$. The second one is $\log(1-x)$. The first one is$$x\sum_{n=1}^\infty nx^{n-1}=x\left(\sum_{n=1}^\infty x^n\right)'=x\left(\frac x{1-x}\right)'=\frac x{(1-x)^2}.$$
Now, let us take $f(x)=\sum_{n=0}^\infty\frac{x^n}{n+1}$. Then $$xf(x)=\sum_{n=0}^\infty\frac{x^{n+1}}{n+1}=\log(1-x).$$ Therefore,$$f(x)=\begin{cases}\frac{\log(1-x)}x&\text{ if }0<|x|<1\\ 1&\text{ otherwise.}\end{cases}$$
Answer: There's not really a "standard way" as much as there's a collection of tricks that sometimes work, and then having enough experience to be able to guess at which tricks could work in a particular case.
For $\sum_{n=0}^{\infty} \frac1{n+1}x^n$ the main trick is termwise differentiation. If we multiply the function by $x$ we get
$$ x f(x) = \sum_{n=0}^{\infty} \frac{1}{n+1}x^{n+1} $$
where the coefficients disappear when we differentiate, so
$$ \frac{d}{dx}(x f(x)) = \sum_{n=0}^{\infty} x^n $$
The right-hand side is a geometric series which you hopefully know how to sum. Then you can integrate both sides, giving you an expression for $x f(x)$, and divide by $x$. Finally, at this point you can adjust the constant of integration such that $f(0)$ has the right value (namely the constant term of the series you started out with).

For $\sum_{n=1}^\infty (n+\frac1n)x^n$ you would split it into $\sum_{n=1}^\infty nx^n$ and $\sum_{n=1}^\infty \frac1n x^n$. The latter of these can be handled the same as before; for the former we can turn it around and integrate term for term. We get
$$ g(x) = \sum_{n=1}^\infty nx^n \\
\frac{g(x)}{x} = \sum_{n=1}^\infty nx^{n-1} \\
\int \frac{g(x)}{x} dx = \sum_{n=1}^\infty x^n $$
and after applying the rule for a geometric series (again) you just have to differentiate each side symbolically and multiply by $x$.


Not able to receive Angular js events

Question: Please have a look at this simple fiddle: http://jsfiddle.net/tgbpy/11/
I am not able to emit the event. I need to do this simple thing to do without creating  a shared service. What am I doing wrong?
Answer: The controller1 and controller2 are are not nested. They are peers and come under the rootScope.

...

...

So when you emit an event from controller1, it wont reach controller2, but will only reach the parents(in this case, it will reach rootScope).
In case controller1 is declared within controller2, then your code should work.

  ..

...

  ..

Answer: To add to what @manoj was telling you
here is a fiddle that works
http://jsfiddle.net/tgbpy/13/
When you want to publish a message you call $rootScope.$broadcast unless the two controllers are nested. If you do $rootScope.$broadcast any scope wherever it is will get it.
Comment: Alternatively, if you want to broadcast less globally, but still hit where you are and its siblings, you can do $scope.$parent.$broadcast. (That also sends to the parent, obviously.) As it happens, I just put together a demo to clarify messaging with nested controllers for myself: http://jsfiddle.net/davemerrill/HQBFr/

Not able to receive Angular js events


Which is more efficient, more code or more conditional checks?

Question: I am doing the 7th exercise on 10 Algorithms To Solve Before your Python Coding Interview. It is about moving the zeroes of a list to the end. I thought of writing a function that moves those zeroes to the end or start based on a boolean argument.
def move_zeroes(numbers, to_start = False):
    pass

The idea in my mind for the move-to-end case was this.
def move_zeroes(numbers):
    for i in numbers:
        if i == 0:
            numbers.remove(i)
            numbers.append(i)

Extending this, I came across two choices.
More code, less conditional checks
def move_zeroes(numbers, to_start = False):
    if to_start:
        for i in numbers:
            if i == 0:
                numbers.remove(i)
                numbers.insert(0, i)
    else:
        for i in numbers:
            if i == 0:
                numbers.remove(i)
                numbers.append(i)

Less code, more conditional checks
def move_zeroes(numbers, to_start = False):
    for i in numbers:
        if i == 0:
            numbers.remove(i)
            numbers.insert(0, i) if to_start else numbers.append(i)

Does there exist a way between these? Can I have less code and less conditional checks? Also, how does this scale for larger lengths of lists?
As a secondary question, in case this is not possible, what is the practical way to do this particular example, keeping in mind memory and extra lines? In other words, which of the two tradeoffs is better than the other?
EDIT 1: Rename list parameter to numbers on the suggestion of @aaossa.
Comment: Note that calling `list.remove` while iterating over `list` is going to cause problems.
Comment: The article keeps talking about "solving" *algorithms* (even in the title). Gives me very little faith in the author.
Comment: The two codes are equally performant.
Comment: Try to avoid using variable names that match class types. That means, do nor name your list `list`. This could have unintended effects if you try to create a list inside one of your functions using `list(something)`
Comment: So does the equal performance mean that Python does not run the if else repeatedly, which is not contributing to the running time?
Comment: That's for the OP to decide. How you fix the iteration issue will affect how you refactor the code, though.
Comment: As @luk2302 said, both codes have equal performance in Python. This means that the more readable code is the best.
Comment: @luk2302 Do you mean because the better performance of the first one is insignificant?
Comment: Going with what others said, long lines in python are not preferred. So in my opinion the first one is more readable.
Comment: Do neither. Functions are first-class objects: set `f` to an appropriate function *before* the loop, then call `f(i)` unconditionally inside the loop.
Comment: Interestingly, it appears to be wrong only for one of the two cases.
Comment: @chepner What would you make `f` when `to_start` is true?
Comment: @chepner With `lambda i: list.insert(0, i)`, it does become noticeably slower in my tests.
Answer: Continually calling remove() (notwithstanding the fact that you shouldn't do that on a list that you're currently iterating over) could be very inefficient as the list has to be scanned from its first element until such time as the remove criterion has been matched.
I propose this:
alist = [1,0,0,2,0,3,0,4,0,5]

def move_zeroes(lst):
    # build a list from all the non-zero elements of the input list
    newlist = list(filter(None, lst))
    # the difference in the lengths of the original and new list
    # will be the number of zeroes that were not copied
    nz = len(lst) - len(newlist)
    # now extend the new list with a list of zeroes of appropriate
    # length and copy into the address space of the given parameter
    lst[:] = newlist + [0] * nz

move_zeroes(alist)

print(alist)

Output:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

Answer: list2 = [1, 0, 0, 2, 0, 3, 0, 4, 0, 5]
temp = 0
for i in range(len(list2)):
    for k in range(i+1, len(list2)):
        if list2[i] == 0 and list2[i] < list2[k]:
            temp = list2[i]
            list2[i] = list2[k]
            list2[k] = temp

print(list2)
Comment: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] your answer will be like this and you won't need any use of an in-built function and can still easily convert the code into a function
Comment: Please [edit] to update your answer instead of commenting.
Comment: Whilst this is functionally correct it's very inefficient. With that dataset you need 45 comparisons. Consider what happens with larger datasets and bear in mind that the original question is about efficiency
Comment: thank you very much I will work on the solution you gave, thanks


Stuck On Proof, I don't know how to continue or correct.

Question:
I know for this question, you can choose to make n = 2j or 2j+1, for some j of Integers. But I get $$j < \frac{1}{2}$$ and I know that I am doing this wrong because this value isn't an integer. How would you solve this proof?
Comment: Keep an eye on what tags you use.  All of your previous tag selections were entirely unrelated.  Proof-Explanation should only be used if you have a complete proof of someone else's that you have questions for clarification about.  Solution-verification is if you have a complete solution of your own that you want to check for correctness and ask for critiques on.  Linear-algebra and Calculus are about their own subjects respectively, this question not being a part of the subject material of those classes, and so on.
Comment: Yes, $n=0$, so $3n-2$ is even
Comment: As for showing that $1-n^2>0$ implies that $n=0$., rearrange to see this is equivalent to $1>n^2$.  Then, recall that $n^2\geq |n|$ for all integers $n$.  For every nonzero integer $n$ you have $|n|\geq 1$ and so you have for every nonzero integer $n$ that $n^2\geq |n|\geq 1$ is not strictly less than $1$, thus $n$ is not non-zero.  It is easy to check however that $n=0$ does satisfy the condition, showing that $1-n^2>0$ is true if and only if $n=0$.
Comment: Welcome to Mathematics Stack Exchange.  What is $n$ if $n\in\mathbb Z$ and $1-n^2>0$?
Comment: Well, what do you mean exactly? I understand the first half of what you are saying but what does the 2nd portion mean exactly? Also, thank you.
Comment: Does this mean that n = 0?
Comment: OH! I get it now because if n was negative then it'd be false. Thank you!
Comment: @JMoravitz I am very sorry I just realized this. This was under my algebra calculus.
Comment: "But I get
$j<\frac 12$
and I know that I am doing this wrong because this value isn't an integer" But that's not an equal sign.  Its a less than sign.  And $0 < \frac 12$.  And $-1 < \frac 12$ and $-2 < \frac 12$.  etc.
Answer: Note that $1-n^{2}>0$ means $n^{2}<1$, so $n$ must be $0$. Then, $3n-2 = -2$ is an even integer. $\blacksquare$
Answer: The only value of $n$ that satisfies the left side of the implication is $0$. For this value, $3n-2=-2=2(-1)$. So the statement is true.
Answer:
But I get
$j<\frac 12$
and I know that I am doing this wrong because this value isn't an integer

That's less than sign, not an equal sign.  There are plenty of integers that are less than $\frac 14$.
but that's not all you get.
So if $n = 2j$ and $n$ is odd then $1 -n^2 > 0$ so $1-4j^2 >0$ so $4j^2 < 1$ so $j^2 < \frac 14$.
If $j\ge 0$ then $0\ge j \le \frac 12$ but  if $j< 0$ then $-j \le \frac 12$ or in other words $-\frac 12 < j<0$.  So you have $-\frac 12 < j < \frac 12$.  Now there is only one integer between $-\frac 12$ and $\frac 12$.  So $j = 0$. and $n=2(0)=0$.
Now if $n = 2j+1$ we do the same thing but it's harder.  $1-(4j^2 +4j +1) > 1$ and so $-4j^2-4j >1$ so $4j^2+4j < -1$ so $j(j+1) < -\frac 14 < 0$.
So that means either $j+1 < 0$ and $j>0$.  Or $j+1 > 0$ and $j < 0$.
$j+1 < 0 < j$ is impossible.  And $j < 0 <j+1$ is impossible if $j$ is an integer.
So $n=2j+1$ is impossible.
but we didn't have to do that.
There's utterly no reason to treat $n$ even differently than $n$ being odd.
Just do $1-n^2 > 0$ so $n^2 < 1$.  So if $n\ge 0$ then $n< 1$ and $0\le n < 1$.  And if $n < 0$ then $-n < 1$ and $-1 < n$ and $-1 < n < 0$.  So either way, $-1 < n < 1$.  And there is only one such integer between $-1$ and $1$ not including $1$ or $-1$.  So $n = 0$.
And if $n =0$ then $3n -2 = 3(0) -2 = -2$ and that is an even number.


Navigate between outlet modals in Angular 5?

Question: I can't handle navigation from one modal window to another.
I have routing module:
{
      path: 'modal1',
      component: Modal1Component,
      outlet: 'modal',
    }, {
      path: 'modal2',
      component: Modal2Component,
      outlet: 'modal',
    }

Main component: MainComponent and in its template i have
<router-outlet name="modal"></router-outlet>
So i am clicking a button that triggers
this.router.navigate([this.router.url, { outlets: {modal: 'modal1'} }]);
And in Modal1Component that is rendered i have a button for modal2. So i want to call modal2 from modal1. How can i tell router to go to the parent route and then call:
this.router.navigate([/* what should be here? */, { outlets: {modal: 'modal2'} }]);
Comment: In the routes you show us, both path and outlet are exactly the same, did you copy it wrong ?
Comment: Sorry, it was typo. I updated it
Answer: It looks like you're just changing the outlet in your router.navigate, but the route itself is not actually changing. And I don't think you actually require a named outlet to do what you're trying to achieve.
When you use router.navigate, you can specify if you want to navigate relatively from somewhere using the ActivatedRoute class. To do so, you have two options :

navigate relatively from you current component and indicate in the path that you want to "go up" one level. Example :
this.router.navigate(['../modal2'], { relativeTo: this.activatedRoute });
navigate directly from you parent. I would personaly use this one but both works. Example :
this.router.navigate(['modal2'], { relativeTo: this.activatedRoute.parent });

I created a mini repo with an example of what (I think) you're trying to achieve on : stackblitz.
Hope that helps
Comment: Thanks, but it didn't help. It just go back to parent url without `(modal:modal1)` in url
Comment: Hum this.router.url indicates the current url, I though your modals were some child components. Try "this.router.navigate('/modal1)" ?
Comment: `this.router.navigate(['/modal1']) ` navigates just to the root path `/modal1`. But i have parent route before it:
`/grandparentRoute/parentRoute/modal1`
Comment: Ok, can you show us what's in this.router.url when you use it to navigate to your modal ?
Comment: And the complete routes config please :)
Comment: Thanks for the repo, but the problem is that i want use something like `this.router.parentUrl` instead of hardcoded string `modal-parent` in `this.router.navigate`
Comment: Url when the `moda1` is active is:
`container/component1/component2/(modal:modal1)`. When i pressed 'open modal2' button i executes function where `this.router.url` is `container/component1/component2/(modal:modal1)`. The same as current url
Comment: Updated my answer and the repo :)
Comment: Thank you. Second variant for me works:
`this.router.navigate([{ outlets: {modal: 'modal2'} }], { relativeTo: this.activatedRoute.parent });`
Answer: Some service can be useful in this case, like in doc:
https://angular.io/guide/component-interaction
Comment: I think it is not good idea to create service for this, because it is only router responsibility


Creating custom alias in IntelliJ IDEA

Question: I'm following along with tutorial videos to learn Java, and I'm using IntelliJ IDEA for my IDE.
If I type sout and then tab, it auto-expands to System.out.println(); , but I have the bad habit of typing south rather than sout.  Is it possible to add south as a custom alias to the IDE for auto-expanding?
Answer: Aliases are not supported, but plain old copy/paste will do the job:

Select the group and paste into it from the group context menu:

Now change the abbreviation to south and define the context.
Comment: Worked like a charm!  Thank you!
Comment: no more window.console.log in javascript just: cmd+j + log :D

Creating custom alias in IntelliJ IDEA


Reporting Services RDLC Table Page Breaks within a Cell with a SubReport

Question: I am having a paging issue with my RLDC report that has a SubReport. The report has a table that prints the header data, then has a SubReport that I placed in a detail cell row within the table to print several detail lines that relate to the header data.
This works as I want. However, the SubReport can span more than one page and this can lead to my problem. When the page is 2/3 full (or even less than 1/4 full) and the SubReport has enough items in it to cause it to go to a second page, the SubReport will then print on the next page. I would rather have it fill out the rest of the page before wrapping to new page.
I have searched all of the options to see if I could figure this out. Is there a setting I am missing somewhere?
Answer: This is a known BUG.  See the following article:
http://social.msdn.microsoft.com/forums/en-US/sqlreportingservices/thread/a68d06f4-2612-47ad-9f07-6d5753315c36/
Comment: Thank you! I must not have been using the right keywords to find this. Now to try something else...


Banshee under Unity stops playing music when hitting the (x) icon

Question: When running Banshee under Unity on Natty (upgraded from Maverick), music plays as expected but when hitting the (x) button on the title bar the window exits and the music stops as well.
Answer: When upgrading the banshee extension providing soundmenu integration was not automatically enabled.  Enabling this extension allows banshee to show itself in the soundmenu indicator and also to close its window without stopping playback.
To change this option open the preferences dialog box (Edit/Preferences on the menu), and select the Extensions tab.  Use the search box to find "sound menu" and ensure that the tick box on the right is selected.
Comment: +1 Note: in contrast to my solution, this will quit Banshee only if not playing music. Anyways, the sound menu extension wasn't enabled on my fresh Natty installation, so this doesn't seem to be default.
Answer: That's the intended behavior.
However, you can install the banshee-extension-appindicator package and enable the Application Indicator for Banshee via Edit → Preferences → Extension. This will prevent Banshee from quitting when closing its window.


math domain error in python when caluclating angles

Question: trying to calculate all kind of triangle's angles by given sides.
I have all the agorithms to do so, one slight problem is having a 'math domain error' which i can't find.
Appreciate any help :)
from math import *
def angles(a, b, c):
    if a + b <= c or a + c <= b or c + b <= a:
        return [0, 0, 0]
    elif a == b == c:
        return [60,60,60]
    tempLst = []
    d = max(a,b,c) #To know which angle is the largest
    if a == d:
        if (b ** 2 + c ** 2) < d**2: #To know wether a triangle is an obtuse triangle
           tempLst.append(round(degrees(acos((c**2 - a**2 - b**2) / (-2 * c * b)))))
           tempLst.append(round(asin(a/sin(tempLst[0])*b)))
        else:
           tempLst.append(round(degrees(asin(c/a))))
           tempLst.append(round(degrees(asin(b/a))))
    elif b == d:
        if (a**2+c**2) < d**2:
            tempLst.append(round(degrees(acos((c**2 - a**2 - b**2)/-2*c*a))))
            tempLst.append(round(asin(b/sin(tempLst[0])*a)))
        else:
            tempLst.append(round(degrees(asin(c/b))))
            tempLst.append(round(degrees(asin(a/b))))
    else:
        if (b**2+a**2) < d**2:
            tempLst.append(round(degrees(acos((c**2 - a**2 - b**2)/-2*a*b))))
            tempLst.append(round(asin(c/sin(tempLst[0])*b)))
        else:
            tempLst.append(round(degrees(asin(a/c))))
            tempLst.append(round(degrees(asin(b/c))))
    tempLst.append(180 - tempLst[0] - tempLst[1])
    return tempLst

Error:
ValueError: math domain error
angles, 25
when trying to input these values: angles(11, 20, 30) ---> "Unhandled exception"
Thank you all
Comment: `(c**2 - a**2 - b**2)/-2*a*b` gives `-41690.0`. `acos` takes a value between `-1` and `1`
Comment: This problem is more related to trigonometry than programming. You have to understand how the trigonometric functions work (in math, not Python). For example, you can't do calculate `acos` for a anything outside of the range `[-1, 1]`
Comment: In the future, please try to debug on your own. It took me less than a minute (and I'm sure that for @ktzr as well) to find the offending line and print the value that is being passed to `acos`
Comment: @DeepSpace will do that next time
Answer: Your trig is off. Use the Law of Cosines
from math import *

def angles(a, b, c):
    if a + b <= c or a + c <= b or c + b <= a:
        return [0, 0, 0]
    elif a == b == c:
        return [60, 60, 60]
    tempLst = [
        round(degrees(acos((a ** 2 + b ** 2 - c ** 2) / (2 * a * b)))), # C
        round(degrees(acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)))), # A
        round(degrees(acos((c ** 2 + a ** 2 - b ** 2) / (2 * c * a))))  # B
    ]

    return tempLst

print(angles(11, 20, 30))
# -> [149, 11, 20]


Performance of having unused descriptors in poll

Question: I have an application (written in C for Linux) which has to listen for a list of 32 TCP sockets on specific ports. These sockets can be 'masked' by the user so that events will no longer be reported for them until they are unmasked.
I am using the non blocking variety of poll (timeout of 0) as my application is not threaded (for backward compatibility reasons unfortunately). My question regards the performance implications of having file descriptors in a poll array which have no events to listen for (events = 0) versus lengthening and shrinking the array dynamically which will presumably be time consuming.
Is poll smart enough to 'skip over' descriptors which do not have any events enabled or will I see a large performance hit from their existence?
Either way, given the sockets will be polled frequently (probably at 100Hz) and changed relatively infrequently (once every second) which of these two methods is likely to see the best performance? Will the overhead of polling descriptors with no events overwhelm the overhead of having to remake the array every time I make a change?
Comment: 100Hz isn't all that frequent since about 1985. You need to test and measure. I don't see why event-less FDs should slow things down significantly. You don't need to use non-blocking select just because you're single-threaded, unless there are other, non-network, things you're supposed to be doing.
Comment: @EJP Unfortunately this -is- the case and the system is performing other tasks too, I am writing an emulator for a real time IPC from the early 90s. However you make a good point about measuring it after trying both, I was just not sure how reliable or platform dependant any results I get may be given I am developing on a very different system to that which will be running the code.
Answer: Looking at the kernel code, I'd say the overhead of having no-event descriptors is small. I do not think you'll find any significant run-time difference between having an array with just one descriptor, and having an array with 32 descriptors with only one having a nonzero event mask.
Having a much larger number of descriptors does mean that the kernel may need to allocate extra pages internally to hold the structures. So, if you had lots-and-lost of descriptors, then pruning the no-event descriptors from the array would make sense.
Manipulating the array (of struct fds) is definitely not time consuming. I wrote some test functions, which use two temporary arrays -- one of struct fds to be filled with descriptors with nonzero event masks, fed to poll(), and another containing pointers so that revents can be updated easily to the original array --, and microbenchmarked them. On x86-64 (AMD Athlon II X4 640), the functions took about 5 clock cycles per descriptor, on arrays of up to a thousand descriptors. Definitely neglible overhead, comparing how much CPU time even basic networking functions consume!
I fear you are suffering from premature optimization. The overall structure of your application or library will have much greater effect on the efficiency and speed of your implementation. So, instead of worrying about this, spend your time making sure your design is robust and sensible.
I've found that trying to make sure that data keeps flowing at all times (not blocking on a specific receive, reading incoming TCP packets as soon as possible, trying to do preparatory work before the corresponding data arrives, so that the data can be immediately pounced upon, et cetera), yields pretty good overall structures.
If you have time, you can always finesse the details after profiling the working application; thus concentrating your efforts to the true bottlenecks.
Comment: Thank you so much, that is a brilliant answer and fully addresses my worries. You also make a good point about premature optimization, I somehow assumed poll would be very time consuming but your results clearly show otherwise. So again, thank you so much for your help.


What can you put in the {}s in a /give command?

Question: What are the things you can put in the {}s in a /give command? I know some like ench and diplay but no others.
Here are the tags that I know how to use:
/give @p leather_boots 1 0 {display:{Name:"Dese Boots Aren't Made For Walking",Lore:["Some Stylish Boots Right Here"]},ench:[{id:0,lvl:15},{id:16,lvl:15}]}

That gives me a pair of leather boots with protection XV and sharpness XV Named "Dese Boots Aren't Made For Walking" with Lore of "Some Stylish Boots Right There".
What other tags can you put on items (like potion effects while equipped or attacked with, custom damage, and stuff like that)?
Comment: Does this answer your question? [What are the basics of commands in Minecraft Java Edition?](https://gaming.stackexchange.com/questions/354614/what-are-the-basics-of-commands-in-minecraft-java-edition)
Comment: If you want armour to add a potion effect, check out [this](http://gaming.stackexchange.com/questions/210372/how-do-i-get-armor-to-add-a-potion-effect)
Comment: Specifically, see the section about NBT.
Answer: The {} part of the give command is the data tag or NBT data of the item. A full list of valid NBT tags for all items is quite extensive and subject to change with every version/snapshot. I will give a brief overview instead, and refer to the wiki for a full list. Basically, the data tag can include anything listed as a subtag of

tag: Additional information about the item, discussed in the below sections. This tag is optional for most items.

This includes:

Enchantments (ench)
Potion effects
The display tag, with things like color, name and lore
Tags for written books
BlockEntityData, holding NBT data of things that have data when placed in the world, such as chests (this alone is a large topic)
...

Note that while you can put a lot of things as data, the game simply ignites everything that makes no sense to it. Putting an author tag on a sword it's no different from putting a banana tag, neither do anything but waste memory.


What are alternatives to an in-floor drain in a laundry room?

Question: Let's say you had a house and, for whatever reason, it was not possible to have an in-floor drain in the laundry room.
Are there alternatives that would ideally provide the same value in case of a leak?
Comment: I have owned houses in the UK and Germany, and a flat in Switzerland.  None has ever had a floor drain in the room with the washing machine (or the dish washer).  I am tempted to reply "just get more reliable plumbing and equipment".
Comment: I have had quite a few houses in the US the only ones that had floor drains were slabs and not all of them had drains none of post and beam homes had floor drains.
Comment: I have a floor drain in a slab . After a few years I plugged it because when the washing machine drained it pumped the water so fast the gravity drain could not handle all the water and it came out the drain . The floor drain has not been needed in 20 years.
Answer: One thing that is an option is automatic shut off valves for the washer that are linked to a water sensor.

Automatic Valves
Above is an example that I have experience with, but they come from several manufacturers and I think there are even "smart home" options that will alert you of a leak as well as turning off valves.  I think I've also seen devices that cut power to the washer when there is a leak to stop it from draining water if the leak is actually a clogged drain rather than a burst hose.
With these valves, you still have to clean up some amount of water, but the problem is greatly reduced to the point of being able to clean up with a simple mop.  Proper baseboard with a good caulking job will keep a small leak from getting behind the walls.
Answer: I believe there is a tray you can purchase that the washing machine sits in that will catch some water, but in the event of a serious leak I don't think it will save you.  I try to not run my washing machine dishwasher when I'm leaving or going to bed, but it's impossible to prevent all equipment breakdowns and you can drive yourself crazy trying.  It's a very good idea to keep a very close eye on new machines for their first few cycles, which is when I've found most problems will occur.


Program Overwriting Array with Null

Question: For a project in school (intro to java), we have to make a program using arrays. I decided to make a login program that stores logins. It works perfectly, except when deleting items. This is my code
    public void delete() throws FileNotFoundException{
    int p;
    c.clear();
    c.print("Please enter a website to delete it's login info: ");
    String delete_name = c.readLine();
    Boolean found = false;

    // Search for the search key, and display the matching elements
    c.println("Searching for " + delete_name + "...");
    for (int i = 0; i < pass.length; i++)
        if (pass[i][0].equals(delete_name)) {
            c.println("Deleting login for " + pass[i][0]);

            String new_array[][] = new String[pass.length - 1][3];
            //remove an element
            for (int w = 0; i < new_array.length; i++)
                for (int j = 0; j <= 2; j++) {
                    p = w;
                    if (i >= p) {
                        new_array[w][j] = pass[w + 1][j];

                    } else {
                        new_array[w][j] = pass[w][j];

                    }
                }

            found = true;
            pass = new_array;
        }

    if (found == false) {
        c.println("No luck! " + delete_name + " wasn't found, please try again.");
        delete();
    }
        fileWriter();

}

When it writes to the file, anything after the part that should have been deleted gets changed to "null".
Sorry if the format is awful, I'm just starting with java :) Any help is greatly appreciated, thanks!
Comment: You cannot set one array (pass) equal to another (new_array). See this thread: http://stackoverflow.com/questions/7882074/how-do-you-set-one-arrays-values-to-another-arrays-values-in-java
Comment: Btw I'm referring to the line "pass = new_array". Instead try "pass = new_array.clone();"
Comment: @Arman I do it in my code other places which works fine. It was actually in the course

`// Step 3: assign the new array to the old array
         grocery_list = new_array;`
Comment: That is not correct though, is this in a book? For example, having one array (arr1) and another (arr2), this "arr1 = arr2" will NOT copy arr2 into arr1. Instead it makes the two arrays refer to the same thing. Read the accepted answer in this thread : http://stackoverflow.com/questions/5617016/how-do-i-copy-a-2-dimensional-array-in-java
Comment: @Arman I changed it to .clone() but it still overwrites anything following the deleted section with "null"

Also it is on the website in sample code where it shows that
Answer: When deleting a row of a 2D array in Java, you can use this shortcut (no for-loops needed)
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
//Remove row at index of "delete_name":
for(int i = 0; i < pass.length; i++){
  if(pass[i][0].equals(delete_name)){
    tempArr.remove(i);
  }
}
String[][] new_array = tempArr.toArray(new String[][]{});

However, this solution only works if you are only deleting one object in the List. I would suggest looking into "iterators"  to make this solution better.
EDIT:
Here is an example with an iterator
    String[][] pass = new String[][]{{"Name","data1","data2"}};
    List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
    for (Iterator<String[]> iterator = tempArr.iterator(); iterator.hasNext();) {
        String id = iterator.next()[0];
        if (id.equals(delete_name)){
            iterator.remove();
        }
    }

Comment: Thanks, I used the first one since I need to get this project done ASAP. I will definitely look into iterators though. Got it working with a few modifications. Thank you!

Program Overwriting Array with Null


kivymd app crashes on android phone ModuleNotFoundError: No module named 'PIL'

Question: My Kivy app crashes on launch on android phone.
buildozer logcat shows the following error:
02-21 17:09:58.777 14941 14979 I python  :  ModuleNotFoundError: No module named 'PIL'
02-21 17:09:58.777 14941 14979 I python  : Python for android ended.

Here are my buildozer.spec requirements:
requirements = python3,kivy==2.0.0,git+https://github.com/HeaTTheatR/KivyMD.git,sdl2_ttf==2.0.15,python-dateutil,requests,urllib3,chardet,idna,plyer,android,jnius,oscpy

As I understand, only the KivyMD depends on PIL.
The app works perfectly on my mac and WAS working before on the android phone. The error just started to occur. So, I'm really confused and would appreciate any help.
Thanks in advance!
Answer: As you might already know, KivyMD depends on PIL, not Kivy. You are using the latest version of KivyMD using git in your app, which depends on PIL. To remove the error just add pillow in the requirements of your buildozer.spec file.
Comment: Hi, I've tried that, but then the apk wouldn't compile, buildozer crashes.
Comment: It should work fine. Can you post the error? Did you add `PIL` or `pillow`? You should add `pillow` not `PIL`
Comment: So, when I add pillow to the buildozer.spec file I get: "raise CommandNotFound(k)
sh.CommandNotFound: cmake". I've read that there is no recipe for pillow yet. But the app was compiling and running on android like 3 days ago...
Comment: `sudo -H apt install cmake`
Comment: when running `sudo -H apt install cmake` I get: `Unable to locate an executable at "/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/apt" (-1)`. So I've installed the cmake with binary file from the official website. But still the same error in buildozer
Comment: you shouldn't get this error. Wait are you on mac?
Comment: Yes) I've installed `cmake` with `homebrew`. And added `pillow` to `buildozer.spec`. The apk compliles, but the app still crashes on launch. Although, this time logcat doesn't show any errors. But since you've helped with the error "No PIL module" I'm gonna accept your answer
Answer: If you are still not getting the desired result after following the correct answer, do refer to the requirements specidied in buildozer.spec file for the KivyMD-kitchen_sink app in the repo.
This is the link -> Kitchen_Sink_Repo
Tip
If, after changing the requirements you still see your app crashing, run the following command(s)
buildozer android clean
buildozer android debug deploy run

Why?
Because when buildozer installs the earlier specified requirements, it is quiet possible that it installs versions that are not matching your apps specifications. So clean it and then run.
You should now be good to go.


compiling and executing a procedure from another procedure

Question: I've written a basic test code for a procedure as follows
create or replace procedure getDetails
AS
output_detail varchar2(30);
detail_you_need varchar2(30);
name_of_player varchar2(30);

BEGIN

select &detail_you_need into output_detail from players where name ='&name_of_player';
dbms_output.put_line(UPPER(output_detail));

END;
/

Im trying to compile and execute it from a another procedure as follows
create or replace procedure getPlayerInfo
as
BEGIN

set serveroutput on;
dbms_output.put_line('Enter the name of the info and the player you want to know the detail of, when prompted...');

@getDetails.sql;
execute getDetails;

END;
/

Individually the code compiles and executes accurately but while doing so from getPlayerInfo it gives an error as follows
SQL> show errors
Errors for PROCEDURE GETPLAYERINFO:

LINE/COL ERROR
5/1      PL/SQL: SQL Statement ignored
5/5      PL/SQL: ORA-00922: missing or invalid option
8/1      PLS-00103: Encountered the symbol "CREATE" when expecting one of
     the following:
     ( begin case declare end exception exit for goto if loop mod
     null pragma raise return select update while with
     <an identifier>
      << continue close current delete fetch lock
     insert open rollback savepoint set sql execute commit forall
     merge pipe purge

how do i resolve this?
Comment: You need to look for basic PLSQL tuts.
Answer: You can't just call script to create procedure inside another procedure. If you need to execute create procedure statement you should do it via execute immediate. Something like:
begin
  execute immediate 'create or replace procedure proc1 is begin null; end;';
end;

Another thing is logic of your code. If you need a procedure to get player details you shouldn't create it every time but rather create procedure that takes palyer name as parameter. Something like:
procedure p1 (name varchar2, detail varchar2) as
AS
  output_detail varchar2(30);
BEGIN
  execute immediate 'select ' || detail || ' into :output_detail from players where name = ''' || name || '''' into output_detail;
  dbms_output.put_line(UPPER(output_detail));
END;
/

And then call it by:
call p1('column_name','player_name');

EDIT
create table players (name varchar2(20), detail varchar2(20));
insert into players values ('Bale', 'Welsh');

create or replace procedure p_det (name varchar2, detail varchar2) as
  output_detail varchar2(30);
BEGIN
  execute immediate 'select ' || detail || ' into :output_detail from players where name = ''' || name || '''' into output_detail;
  --dbms_output.put_line('select ' || detail || ' from players where name = ''' || name || '''');
  dbms_output.put_line(UPPER(output_detail));
END;
/

call p_det('Bale','detail');

Comment: thank you ... that should work.. i was trying to narrow down the work of compiling and executing the procedure in 2 gos by calling a single procedure... your code should do the job . i was unaware of 'execute immidiate'. Appreciate your help!
Comment: create or replace procedure getinf(player varchar2, detail varchar2)     as
    output_detail varchar2(30);

    begin
    execute immediate 'select' || detail || 'from players where name = ' ||      player into output_detail;
dbms_output.put_line(UPPER(output_detail));
end;
/      on call getinf('Bale','club'); it gives an error
SQL> call getinf('Bale','club');
call getinf('Bale','club')
     *
ERROR at line 1:
ORA-00900: invalid SQL statement
ORA-06512: at "SYSTEM.GETINF", line 6
Comment: @codepoetly You're missing whitespace after select and before from. Thse whitespace are important.
Comment: did the changes but it generates another error. i tried searching for the resolve on nete but no go... the error is as follows..............
SQL> @getinf.sql;

Procedure created.

SQL> call getinf('Bale', 'club');
call getinf('Bale', 'club')
     *
ERROR at line 1:
ORA-00933: SQL command not properly ended
ORA-06512: at "SYSTEM.GETINF", line 6
Comment: I found the solution. Had to concatenate SINGLE quotes for the name variable in the EXECUTE IMMEDIATE. It now compiles and completes the call too though the output is not displayed even after set serveroutput on!!
Comment: what additional should i do to get the output displayed?
Comment: @codepoetly `dbms_output.put_line(UPPER(output_detail));` is displaying value. If you're using SQL Developer to see the output you need to do that: https://www.youtube.com/watch?v=FeeNVnXiRIg
Comment: Im not using sql developer... the output is not displayed .. but i get the msg 'call completed' and serveroutput is also on..
Comment: @codepoetly Do you have `into output_detail` in your execute immediate? Beacuse this part says that result of query is returned into variable which later gets printed.
Comment: execute immediate 'select ' || detail || ' from players where name = ' || '''||player||''' into output_detail;        ..... n just to make sure its copied i also added another dbms test stmt before dbms_output.put_line(UPPER(output_detail));.... but even that is not displayed... so something needs to be modified here i suppose
Comment: @codepoetly You're right there was `:output_detail` missing in procedure. Try version after EDIT.
Comment: yes it displays the output and the test dbms msg is also displayed now....  what was the fix... im a bit confused even after reading the code.
Comment: i get the point that the output of execute immediate was not copied into output_detail but how did it affect the test dbms?
Comment: @codepoetly Fix was ` into :output_detail` added to select query. So it needs to be twice oin statement. Once as part of PL/SQL select and second as part of execute immediate syntax


How to change props to state in React Hooks?

Question: In Simple react class component we used to change the props to state this way:
constructor(props) {
    super(props)

    this.state = {
      pitch: props.booking.pitch,
      email: props.booking.email,
      firstName: props.booking.firstName,
      arrivalDate: props.booking.arrivalDate
    }
}

But I am not aware of how to do it in new feature as Hooks, but I am trying to do it this way.
const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(null)

useEffect(() => {
    setDescription(initialDesc)
  }, {})

 function handleChangeVariance(newVariance) {
    setDescription({
      ...description,
      template: {
        ...description.template,
        variance_name: newVariance,
      },
    })
  }

}

Basically, I just need to change description props, which coming from another parent component to turn to state. Pls, could you show me how to do it in new way as Hooks way?
Comment: First concern here was that you're copying props into a local state. Why is that necessary?
Answer: The problem in your code is with {}.
UseEffect hook expects and array, not an object. Use [initialDesc] instead.
This is how you reset component state when props change
const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(null)

  useEffect(() => {
    setDescription(initialDesc)
  }, [initialDesc]);
}

This is how you initialize component state to prop value on first render only
const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(initialDesc);
}

Comment: this is the correct answer to handle external change of the property value. without this it will not get synced
Comment: This! I had a component with pageNumber changing externally and `useState(props.initialPageNumber)` would not use the latest value due to some React hidden optimizations. Even though this was two distinct component instances in two separate places of the page. One with `initialPageNumber={1}` and the other with `initialPageNumber={3}`
Answer: You can pass your initial state as first argument to useState like this:
const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(initialDesc)

  ...

Comment: sorry but it did not help
Comment: It's worth noting that this is only fine if the `description` prop passed to the `GenerateDescHook` component never changes and also that the code in the OP has the same drawback. Unless you can guarantee that (which is a dangerous assumption IMO), [this](https://stackoverflow.com/a/55793169/1205753) is probably the better answer.
Comment: @Feruza This is actually the way this should be done, this is hook counterpart to your class component. If it doesn't work for you, you're possibly doing something wrong.
Comment: @Feruza Why did you accept this answer? If the parent state changes, child state will remain unchanged. The useEffect solution with more votes is what I came here for at least.
Answer: The initial value of your state is the one passed into useState :
const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(initialDesc)

As the documentation states :
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (

You clicked {count} times

      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>

  );
}

Is the equivalent of :
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (

You clicked {this.state.count} times

        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>

    );
  }
}

Comment: how do you get the state object? not just an individual prop
Comment: What do you mean by state object ? the variable containing your value is `description`. And hooks don't have any parent variable containing all state values
Answer: It is difficult to achieve a state which depends on prop value and at the same avoid unnecessary re-renders.
Here is my attempt in creating such a hook:
/**
 * Replacement for useState which depends on prop value and avoids unnecessary re-renders.
 */
export function useStateBasedOnProps(propValue) {
    const [, update] = useState(false);

    const [state, setState] = useMemo(() => {
        const state = {};
        return [
            state,
            (value) => {
                if (value instanceof Function) {
                    state.value = value(state.value);
                } else {
                    state.value = value;
                }
                update((tick) => !tick);
            }
        ];
    }, [update]);

    if (state.prevPropValue !== propValue) {
        state.prevPropValue = propValue;
        state.value = propValue;
    }

    return [state.value, setState];
}

Here is a usage example:
function IncButton({initialValue}) {
    const [value, setValue] = useStateBasedOnProps(initialValue);
    const increment = useCallback(() => setValue((prev) => prev + 1), [setValue]);
    return <button onClick={increment}>Click to increment: {value}</button>;
}

Full example: https://gist.github.com/mdevils/b861610780300784292194f65886517a


ChannelParticipants object is not subscriptable

Question: Have "ChannelParticipants" object is not subscriptable error in telethon.
I am trying to scrape members to CSV file from telegram group. Please help! Here is my code
for chat in chats:
    try:
        if chat.megagroup == True:
            groups.append(chat)
    except:
        continue
try:
    print('Choose a group to scrape members from:')
    i=0
    for g in groups:
        print(str(i) + '- ' + g.title)
        i+=1

    g_index = input("Enter a Number: ")
    target_group=groups[int(g_index)]

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group)
except TypeError:
    print("smth")
print('Saving In file...')
with open("members.csv","w",encoding='UTF-8') as f:
    writer = csv.writer(f,delimiter=",",lineterminator="\n")
    writer.writerow(['username','user id', 'access hash','name','group', 'group id'])
    for user in all_participants:
        if user.username:
            username= user.username
        else:
            username= ""
        if user.first_name:
            first_name= user.first_name
        else:
            first_name= ""
        if user.last_name:
            last_name= user.last_name
        else:
            last_name= ""
        name= (first_name + ' ' + last_name).strip()
        writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id])
print('Members scraped successfully.')

Can't find anything in google. Everything working with small groups.
Answer: Try this
      queryKey = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','0','1','2','3','4','5','6','7','8','9',' ','','~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/']

      for key in queryKey:

          while True:
          participants = client(GetParticipantsRequest('channel/group_name', ChannelParticipantsSearch(key), 0, 200, 0))

          if not participants.users:
             break
          for users in participants.users:
             print(users)

          offset += len(participants.users)

Answer: Setting limit to number of users worked for me-
await client.get_participants(group, aggressive=False, limit=2000)

You can increase the limit.


libspe vs. libspe2? What's the difference?

Question: I've been doing some experiments with the Cell processor in a PS3 that I have sitting around and I've run across an issue. It appears that there are two versions of the main SPE management library, libspe and libspe2. What is the difference between them? From what I can tell the main difference is that in libspe they rolled their own threading code, whereas in libspe2 you have to integrate the libspe with the pthreads library to achieve multiple threads. Is there any reason that one is better than the other? What is being gained/lossed/changed between the two?
Answer: Alright, so it looks like libspe2 is the way to go. What I noted above about threading is pretty much the main difference, libspe2 provides a much more flexible threading model. Also, libspe is deprecated as of SDK 2.1 and 3.1 is the current version, so starting any new projects with libspe is probably a bad idea.
There is a good article with examples on the IBM site here.


Objective C transformedMetadataObjectForMetadataObject make unstable size when i use it to resize preview layer

Question: Issue is unstable (size jump between two sizes at every update) size returned by transformedMetadataObjectForMetadataObject only if i use it to resize previewLayer.
<code>    for(AVMetadataObject *metadataObject in metadataObjects) {
        if([metadataObject.type isEqualToString:AVMetadataObjectTypeFace]) {
            // Take an image of the face and pass to CoreImage for detection

            AVMetadataObject *metadataObjectR=[previewLayer transformedMetadataObjectForMetadataObject:metadataObject];

            previewLayer.bounds = CGRectMake(previewLayer.bounds.origin.x,previewLayer.bounds.origin.y, metadataObjectR.bounds.size.width,metadataObjectR.bounds.size.height);
</code>
Code for creating previewLayer (previewViewLayer is CALayer)
<code>[captureSession addInput:vInput];
[captureSession setSessionPreset:AVCaptureSessionPresetPhoto];

previewViewLayer = [self.view layer];
[previewViewLayer setBackgroundColor:(__bridge CGColorRef _Nullable)([UIColor blackColor])];
previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession];
[previewLayer setFrame:[previewViewLayer bounds]];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[previewViewLayer addSublayer:previewLayer];
</code>
Answer: I don't know what are you want to do.The function transformedMetadataObjectForMetadataObject,return the metaDataObject which in the previewLayer coordinates,so the bounds of it is the metaDataObject`s frame.But you use this frame to set the previewLayer's bounds.The previewLayer's frame should not change,because it is use to preview the camera.You should use the new metaDataObject's bounds to change the frame of the layer indicate the face.


Composition of monadic functors may not be monadic

Question: Let $U\colon \textbf{AbGp}\longrightarrow \textbf{Set}$ be the forgetful functor. By the Crude Monadicity Theorem, it is monadic.
Any reflection is monadic, so $I \colon \textbf{tfAbGp}\longrightarrow \textbf{AbGp}$ is also monadic.
I am trying to show that its composite is not monadic. The left adjoint of $U$ is the free functor and the explanation that I have found is the following: Free abelian groups are torsion free and so the monad on $\textbf{Set}$ induced by the composition is isomorphic so that induced by $F$ and $U$.
However, I do not understand why that contradicts the fact of being monadic. The comparison functor in the first case is $K\colon \textbf{AbGp}\longrightarrow \mathcal{C}^{\mathbb{T}}$ sending $B$ to $(UB, U\epsilon_{B})$, so it is faithful, full and essentially surjective (because the forgetful functor is monadic).
In the second case the comparison functor would have domain $\textbf{tfAbGp}$, so I have been thinking why can't that be faithful, full or essentially surjective. Nevertheless, I do not find any example.
Can anyone help me, please?
Comment: is $U$ going the wrong direction?
Comment: Sorry, it is going the opposite direction. Thank you very much :)
Answer: The point is that the left adjoint to the forgetful functor
$$U'=U \circ I \colon \mathbf{tfAbGp} \to \mathbf{Set}$$
is basically the free abelian group functor, i.e. the left adjoint to $U$ with the codomain restricted to $\mathbf{tfAbGp}$.
This implies that the monad associated to $U'$ is the same monad associated to $U$, i.e. the free abelian group-monad, and the comparison functor from $\mathbf{tfAbGp}$ sends the torsion free groups in torsion free groups, i.e. it is not essentially surjective and so it cannot be an equivalence.


How can I repair uneven tile grout?

Question: I had ceramic installed in my kitchen about a year ago. In 75% of the kitchen the grout is not level with the rest do I have to remove all the grout and start over or can it be floated to fill in the low places
Answer: All the existing grout won't need to be completely removed but you'll need to use a grout removal tool to cut into the existing grout so that your new grout has a little more to grab on to.
Comment: I wonder if a polymer grout would allow direct placement without the need to cut in any?
Comment: It may... My worry is of bonding of the new grout to old sealed grout. You'll either end up with a dry joint where the new grout will eventually fall out or the new grout can be wiped "off" during normal cleaning...

How can I repair uneven tile grout?


Sizeof in c porting to Java

Question: I have a code in C like this
<code>skip=(unsigned long) (st_row-1)*tot_numcols;
fseek(infile,sizeof(cnum)*skip,0);
</code>
Now i have to port it into Java How can I do That.The "cnum" is a Structure in C so I created a class in Java.But about that fseek how can i point to the exact position in File in Java.
Comment: [`FileChannel.position`](http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#position(long)) ought to do the trick.
Comment: yes It is the only way to to point in a file in Java but what about the size it should move?I dont know how to do that
Answer: Your C design is broken, and you can't do what you apparently want in Java.
It appears that you're storing information out of C structs by blindly dumping the pointer to disk. In addition to being difficult to debug, it's prone to break completely with any change that makes the compiler decide to pack the struct differently, including in particular compiling identical code for 32-bit and 64-bit or little- and big-endian targets. Instead, you should always explicitly serialize structured data. Human-readable formats are best unless there's a very large amount of data.
Java simply doesn't permit this kind of attempt. The Java memory model explicitly hides information about runtime memory packing, and the JVM has wide latitude to organize memory management as it sees fit.
Instead, define a clear format for saving your data, including endianness, and use that from both languages.
Comment: Or better yet: Use one of the existing, battle tested serialization formats with bindings/libraries existing for C and Java.
Comment: @datenwolf .. or if you are going to do it yourself, read how these libraries work, before trying to invent a better wheel.

Sizeof in c porting to Java


Calling a standard library function in signal handler

Question: Why is calling a standard library function inside a signal handler discouraged?
Comment: Anecdote: I worked on a project that used an Access database.  We had a signal handler that called printf(), but instead of writing to stdout, it would write to the .mdb file, hosing the database beyond repair.  Needless to say, this was inconvenient.
Comment: By discouraged, I meant its undefined behavior.
Comment: But, then also when I use functions like printf(), the code just runs fine...
Answer: This is explained in the GNU LibC documentation.

If you call a function in the handler, make sure it is reentrant with respect to signals, or else make sure that the signal cannot interrupt a call to a related function.

And just in case, here's the Wikipedia page on reentrant functions.

A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently).
Answer: Its not only re-entrancy issues, depending on the signal being services you also want to avoid inadvertent calls to malloc() (i.e. asprintf()) and other variadic expansion (i.e. printf()).
Answer: It is all running fine and stuff, until you run into some mysterious bugs which are totally untraceable :)
man 7 signal will give you a list of system calls which are safe to call from a signal handler. It is described in POSIX as well.
Answer: Because the library function may not be reentrant.