text:
Q: Can't delete the filter called My Filter I'm unable to get rid of a filter that goes by the name of "My Filter".  This is the default name you get when you click on New Filter.  There's a clickable "Delete this filter", which leads to a confirmation question on whether you really want to delete it.  Clicking "Yes" leads you back to the "New Filter" Screen,  with a new filter named "My Filter".
I don't know whether this is the same filter I was just trying to get rid of,  or whether it got rid of the old one, and now is making a new one with the same old name.  Either way, I'm stuck.

A: Adding details in hopes of getting developer attention.
Reproducing the issue from a clean state.
I believe this may be how to reproduce this issue. I can't verify, because I'm already in the broken state.

*

*Start with at least 1 existing, valid filter (with tags and everything).

*Click New Filter.

*Instead of finishing that filter, click on the existing, valid filter.

*Delete the existing, valid filter.

*There should be a My Filter in the reloaded page, even though you never finished creating it. Try to delete My Filter now.

*This might be what spawns My Filter (2). (Not as sure about this part.)

Reproducing the issue from the broken state.
However one gets to the broken state, one can easily keep reproducing more and more My Filters simply by clicking New Filter while viewing an existing, valid filter.

Does finishing the creation of those filters allow them to be deleted? (No.)
These are screenshots from before I created a bunch of My Filters. This is what you see when looking at My Filter.

If we finish creating the filter, can we delete it? Let's make it into a rust filter...

Clicking "Save Changes"...

Clicking "edit" and "delete this filter"...

Huh? The page reloads and My Filter is back.

I've also tried finishing the creation of all the My Filters, in case having any unfinished filter was causing the issue. No luck.

A: I did a mistake and clicked "New Filter" button too many times so I found some temporary solution to "delete" not needed "New Filter" from my sight: it is uBlock Origin extension for my browser.
I used uBO's filters to hide "New Filter" position in menu and "New Filter" button to not click it by accident. My current and working uBO filters are:
stackexchange.com##li:nth-of-type(5)
stackexchange.com##[href="/filters/new"]

First line hides "New Filter" (it's 5th one in my case), second line hides "New Filter" button.


text:
Q: Making an ASP.NET application viewable on mobile browsers I have an old ASP.NET web application (Web Forms, no MVC) and I would like to make it "look nice" in mobile browsers, while keeping the current design for desktop browsers.
One of my options is CSS media queries , but then - is there a list of standard screen sizes I should adapt it for?
I also read about Modernizr - but it seems to just detect browser capabilities, and I wouldn't know how to use it for my purposes.
What would be my best bet? Appreciate it.

A: You should take a close look at jquery-mobile which has a lot of built in functions to deal with both changing the display based on device as well as a variety of layouts pre-optimized for mobile views.
Take a look at this link for way more information : http://jquerymobile.com/
However this would not necessarily be easy, depending on the complexity and overall layout of the "normal" web page. However it could easily be implemented to judge what device is being used and then switch to an already defined layout.

A: I recurred to CSS media queries. Here's a nice introduction. Much appreciated.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Make a sum with two random numbers but it must equal the users input I was wondering if it is possible to make a sum from a user input int but the sum must be radom every time.
This is the code that I made :
    public static string genSum(int askedNumber)
    {
        string outputStr = null;

        bool switchOneTwo = false;
        int neededSum = 0;

        int intOne = 0;
        int intTwo = 0;

        while (askedNumber != neededSum)
        {

            if (switchOneTwo == true)
            {
                intOne += 1;
                switchOneTwo = false;
            }
            else
            {
                intTwo += 1;
                switchOneTwo = true;
            }

            neededSum = intOne + intTwo;

            if (neededSum == askedNumber)
            {
                if (neededSum >= 4)
                {
                    Random randomInt = new Random();

                    int tmpIntOne = intOne;
                    int tmpIntTwo = intTwo;
                    int method;

                    //For now only one method
                    method = randomInt.Next(1, 1);

                    if (method == 1)
                    {
                        tmpIntOne = tmpIntOne / 2;
                        tmpIntTwo = (tmpIntTwo * 2) - tmpIntOne;
                    }

                    intOne = tmpIntOne;
                    intTwo = tmpIntTwo;
                }

                outputStr = "(" + intOne.ToString() + "+" + intTwo.ToString() + ")";

                return outputStr;
            }
        }
        return outputStr;
    }

so what I want is that if a user eneters a number for example 20 it will then make a sum :
User enters 20 and presses GO! :
Result :
10 + 10 = 20
12 + 8 = 20
5 + 15 = 20
1 + 19 = 20
3 + 17 = 20
User enters 500 and presses GO! :
Result :
9 + 491 = 500
263 + 237 = 500
300 + 200 = 500
250 + 250 = 500
109 + 391 = 500

A: Create a random number less than the input and the other one will be User-YourRandom
void Foo(int userNumber)
{
    Random r = new Random();
    int firstNumber = r.Next(userNumber - 1);
    int secondNumber = userNumber - firstNumber;
}

You can extend this to support negatives also.
edit getting true randoms
as I4V points out, if you put this in a loop you might get same set of numbers, so instead of calling Random you can use this approach:
void Foo(int userNumber)
{
    int userNumber = 500;

    for (int i = 0; i < 10; i++ )
    {
        int firstNumber = Next(0, userNumber - 1);
        int secondNumber = userNumber - firstNumber;

        Console.WriteLine(firstNumber + "+" + secondNumber);
    }
}

internal static int RandomExt(int min, int max)
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] buffer = new byte[4];

    rng.GetBytes(buffer);
    int result = BitConverter.ToInt32(buffer, 0);

    return new Random(result).Next(min, max);
}

A: foreach (var s in genSum(500).Take(5))
{
    Console.WriteLine(s);
}

public static IEnumerable<string> genSum(int askedNumber)
{
    Random r = new Random();
    while (true)
    {
        var i = r.Next(0, askedNumber);
        yield return i + "+" + (askedNumber - i);
    }
}


text:
Q: How to fix unsafe implementation of HostnameVerifier I have received this warning from Playstore because my code bellow is accepting all hosts

You app is using an unsafe implementation of the HostnameVerifier. And refer a link to Google Play Help Center article for details regarding to fixing and deadline of vulnerability.

@SuppressLint("TrulyRandom")
private static void handleSSLHandshake() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }};

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                Log.i("hostname",""+arg0);
                return true;
            }
        });

    } catch (Exception ignored) {
    }
}

Now the problem is that I don't know how many hosts I need to add in addition to my main host.
when I tried to read hosts used in my app I found that they are many and they came from libraries ( Google ads , applovin , crashlytics , onesignal ...)
Here are examples :

hostname: marcoasensiomadrid.website
hostname: api.crashlytics.com
hostname: ms.applovin.com
hostname: d.applovin.com
hostname: d.applovin.com
hostname: rt.applovin.com
hostname: a.applovin.com
hostname: googleads.g.doubleclick.net
hostname: res1.applovin.com
hostname: onesignal.com
hostname: pagead2.googleadservices.com
hostname: onesignal.com
hostname: api.crashlytics.com
hostname: ms.applovin.com
hostname: d.applovin.com
hostname: d.applovin.com
hostname: rt.applovin.com
hostname: a.applovin.com
hostname: googleads.g.doubleclick.net
hostname: res1.applovin.com
hostname: onesignal.com
hostname: pagead2.googleadservices.com
hostname: googleads.g.doubleclick.net
hostname: googleads.g.doubleclick.net
hostname: prod-a.applovin.com
hostname: track.tenjin.io
hostname: play.google.com
hostname: play.google.com
hostname: a.applovin.com
hostname: res1.applovin.com
hostname: res1.applovin.com
hostname: res1.applovin.com
hostname: pagead2.googleadservices.com
hostname: pagead2.googleadservices.com

How can I Allow all Hosts used by my app and pass the warning at the same time ?

A: Your custom verifier only works for ssl connections established via HttpsURLConnection; most of the third-party libraries will not be involved. At any rate, your problem seems to be that you need to allow some host that is not verified by default, not vice versa. In such case, the following code could help:
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  private final HostnameVerifier systemHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
  private final String hostWithSpecialCertificate = "marcoasensiomadrid.website";

  @Override
  public boolean verify(String hostname, SSLSession session) {
    if (hostWithSpecialCertificate.equalsIgnoreCase(hostname)) {
      X509Certificate certificate = (X509Certificate)(session.getPeerCertificates()[0]);
      final int ALT_DNS_NAME = 2;
      for (String altName : getSubjectAltNames(certificate, ALT_DNS_NAME)) {
        if (systemHostnameVerifier.verify(altName, session)) return true;
      }
      X500Principal principal = certificate.getSubjectX500Principal();
      return systemHostnameVerifier.verify(new DistinguishedNameParser(principal).findMostSpecific("cn"), session);
    }
    return systemHostnameVerifier.verify(hostname, session);
  }
});

this uses private List<String> getSubjectAltNames(X509Certificate certificate, int type) (copy verbatim from OkHostnameVerifier.java).


text:
Q: Dividir String em blocos, considerando apenas letras ou texto entre colchetes Se eu tiver uma String assim:
"Olá, o meu nome é [José Cavalo]"

E eu der split:
{"Olá,", "o", "meu", "nome", "é", "[José", "Cavalo]"}

Primeiramente, temos um problema. No índice 0, temos "Olá,", e queremos separar o "Olá" da vírgula. Depois, eu queria separar a String em blocos, detetando os parênteses retos, e juntando "José" com "Cavalo", ficando "[José Cavalo]", num só elemento (bloco, como explicitado no título)
Eu pensei em usar regex para o caso do bloco:
Matcher m = Pattern.compile("\\[([^)]+)\\]").matcher("Olá, o meu nome é [José Cavalo]");
while(m.find()) {
    System.out.println(m.group(1));
}

Mas o comportamento deste pedaço de código não é o esperado. Se tivermos múltiplos blocos, ele apenas faz o primeiro parêntese reto com o último parêntese reto de todos:
//Consideremos a seguinte String:
String s = "[bloco1] [bloco2]";
//... Aqui vai o código do regex para a separacao ...

//Resultado:
//bloco1] [bloco2

Temos já aqui dois problemas:
O primeiro é o tal problema de "primeiro parêntese reto > último parêntese reto de todos".
O segundo é que ele remove os parênteses retos. Eu não quero isso, pois já tenho uma função separada para os remover.
Não faço ideia nenhuma de como separar a vírgula do "Olá".

A: Na sua regex você usou [^)], que é "qualquer caractere que não seja )". E o quantificador +, por padrão, é "ganancioso" e tenta pegar o máximo de caracteres possível (por isso no caso de ter "[bloco1] [bloco2]", ele pega a string toda, já que você só disse que não podia pegar ), então a regex pode pegar [ ou ] a mais, caso ache necessário - e o comportamento "ganancioso" diz que é para pegar).
Se não quer que pegue os colchetes, inclua-os na classe de caracteres (lembrando de escapá-los com \):
Matcher m = Pattern.compile("\\[([^\\[\\]]+)\\]")
                   .matcher("Olá, o meu nome é [José Cavalo] [bloco 1] [bloco 2]");
while (m.find()) {
    System.out.println(m.group(1));
}

A saída é:
José Cavalo
bloco 1
bloco 2

Se quer que o resultado seja [José Cavalo], [bloco 1] e [bloco 2] (com os colchetes), basta trocar o m.group(1) para m.group(0) (ou apenas m.group(), sem parâmetros - ambos pegam todo o match encontrado).
Você também poderia usar "\\[([^\\[\\]()]+)\\]" (incluir o ( e ) na classe de caracteres), assim a regex não pega colchetes nem parênteses.

Agora para pegar somente Olá (sem a vírgula) você pode usar o atalho \w:
String s = "Olá, o meu nome é [José Cavalo]";
Matcher matcher = Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS).matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Também usei a opção Pattern.UNICODE_CHARACTER_CLASS para considerar caracteres acentuados.
E para pegar tanto a palavra sem a vírgula, quanto o caso dos colchetes, use alternância (o caractere |, que significa "ou"):
String s = "Olá, o meu nome é [José Cavalo] [bloco 1] [bloco 2]";
Matcher matcher = Pattern.compile("\\[([^\\[\\]]+)\\]|\\w+", Pattern.UNICODE_CHARACTER_CLASS).matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Assim, a regex tenta primeiro pegar caracteres entre colchetes. Se não conseguir, ela tenta pegar a sequência de \w.
A saída é:
Olá
o
meu
nome
é
[José Cavalo]
[bloco 1]
[bloco 2]

Um detalhe é que \w também considera números e o caractere _. Se quiser limitar a somente letras, outra opção é usar as Unicode Properties:
Matcher matcher = Pattern.compile("\\[([^\\[\\]]+)\\]|\\p{L}+").matcher(s);

No caso, \p{L} pega todas as letras definidas pelo Unicode (são todas as categorias que começam com "L" desta lista). Só que isso inclui outros alfabetos, como o japonês, árabe, cirílico, etc. Se quiser se limitar a apenas ao nosso alfabeto, outra opção é usar \p{Script=Latin}:
Matcher matcher = Pattern.compile("\\[([^\\[\\]]+)\\]|\\p{Script=Latin}+").matcher(s);

Em ambos os casos, não precisa usar a opção Pattern.UNICODE_CHARACTER_CLASS.


text:
Q: Sorting CSV Data in a Report I'm trying to print a CSV file with List & Label. I need to sort it by one of the columns, however the sort property is not available. If I use a SQL data source, I can sort it. How can I sort the CSV data? My source is
CsvDataProvider csvDta = new CsvDataProvider(@"C:\temp\myData.csv", true, "Data", ';');

using (ListLabel LL = new ListLabel() { DataSource = csvDta})
{
   LL.Design();
}

A: A simple way would be to wrap the CSV data in an InMemoryDataProvider. Try this:
using combit.ListLabel23;
using combit.ListLabel23.DataProviders;

CsvDataProvider csvDta = new CsvDataProvider(@"C:\temp\myData.csv", true, "Data", ';');

// wrap the table in a queryable data source
InMemoryDataProvider dataSource = new InMemoryDataProvider();
dataSource.AddTable(csvDta, "Data");

using (ListLabel LL = new ListLabel() { DataSource = dataSource})
{
   LL.Design();
}

This will give you all the glory of sorting and filtering you require.


text:
Q: Trying to get a rooted Android image in Android Studio with Google Play I'm using Android Studio and it seems that I can only either get an image that allows me to run adb root to get a root shell and doesn't support Google Play, or one that supports Google Play and cannot run adb root because of it being in production mode.
I've taken suggestions from here: Android SDK (Nexus 5X API28 x86) stopping at preparing for setup and installed "Google Play Intel x86 Atom System Image" as shown below:

However, when I go to create a new image, I'm selecting Pixel 2 (with Google Play next to it):

and on the next screen, I'm not quite sure if I'm supposed to select one or the other, but I have tried a few with no luck.

When I install Pie from the Recommended tab with Google Play, I can't establish a root shell. However, when I run it from the x86 tab with Google API, I can establish a root shell but cannot get Google Play working.


text:
Q: What is the best way to use void pointer for returning multiple type variables in C++? I've got base class like that:
class Test {
public:
    virtual void* getValue () {}
};

And then I want to create a couple of derived classes that implements getValue method (they will return different type variables after converting their addresses to void*):
class TestA : public Test {
private:
    int value;

public:
    TestA (int value) : value(value) {}

    void* getValue () {
        int* result = new int;
        *result = value;
        return (void*) result;
    }
};

In this case I'm creating variable to be returned with "new", so I'll have to delete it after using the method:
    TestA testA(5);

    int* toDelete = (int*) testA.getValue();
    int someLocalVariable = *toDelete;
    delete toDelete;

The second way that I've thought about is to create a copy of class member which value I'd like to return and using it only for getValue() method:
class TestB : public Test {
private:
    double valToRet;
    double value;

public:
    TestB (double value) : value(value) {}

    void* getValue () {
        valToRet = value;
        return (void*) &valToRet;
    }
};

Usage of getValue() method is now simpler, but in that case I will have more memory occupied whenever I'm using this class:
    TestB testB(3);

    double someOtherLocalVariable = *((double*)testB.getValue());

Is there any better way to implement getValue() method?
I always know what the type will be, so don't worry about that.

A: You could wrap the Test class in a template.
template <typename T>
class Test {
public:
    virtual T* getValue () =0;
};

class TestA : public Test<int>
{
public:
    virtual int* getValue () { return new int(3); }
};

class TestB : public Test<float>
{
public:
    virtual float* getValue() { return new float(3.2); }
};


text:
Q: Overloading operator * I have a vector3 class which i need to implement different multiplication options ( so i overloaded the operator *) depending of the types that im multiplying.
The problem is that in the last one i get the error:
Description Resource    Path    Location    Type
ambiguating new declaration of 'Pang::vector3 Pang::operator*(const Pang::vector3&, const Pang::vector3&)'  vector3.h   /PangGame/src   line 130

C/C++ Problem
But i have only one operator overloaded that returns vector and muyltiplies two vectors.
Hope you can help ( just to clarify the class vector 3 has threee double numbers ) ex: vector3(double x, double y, double z); )
friend vector3 operator* (const double& number, const vector3& vector)
         {
     vector3 result;
     result.x = number*vector.x;
     result.y = number*vector.y;
     result.z = number*vector.z;
     return result;
         }

 friend vector3 operator* (const vector3& vector, const double& number)
             {
         vector3 result;
         result.x = number*vector.x;
         result.y = number*vector.y;
         result.z = number*vector.z;
         return result;
             }
 //Scalar product: If a = a1i + a2j + a3k and b = b1i + b2j + b3k then
 // a · b = a1*b1 + a2*b2 + a3*b3
 friend double operator* (const vector3& vector1, const vector3& vector2)
 {
         double result;
         result= (vector1.x)*(vector2.x)+(vector1.y)*(vector2.y) + (vector1.z)*(vector2.z);
         return result;
 }

 /* Product: Vector x Vector
  * Example: The cross product of a = (2,3,4) and b = (5,6,7)

 cx = aybz - azby = 3×7 - 4×6 = -3
 cy = azbx - axbz = 4×5 - 2×7 = 6
 cz = axby - aybx = 2×6 - 3×5 = -3
 Answer: a × b = (-3,6,-3)*/
 friend vector3 operator* (const vector3& vector,const vector3& vector2)
                 {
             vector3 result;
             result.x = (vector.y)*(vector2.z) - (vector.z)*(vector2.y);
             result.y = (vector.z)*(vector2.x) - (vector.x)*(vector2.z);
             result.z = (vector.x)*(vector2.y) - (vector.y)*(vector2.x);
             return result;
                 }

A: The problem is that you are trying to overload operator* based on the return type:
double operator* (const vector3& vector1, const vector3& vector2)
vector3 operator* (const vector3& vector1, const vector3& vector2)

This is not allowed because overload resolution takes into account the function signature, which does not include the return type:

3.19 signature [defns.signature]
⟨function⟩ name, parameter-type-list, and enclosing namespace (if any)

One possible solution, if you do want your operator* to possibly yield either a double or another vector3, you can return a proxy type that is convertible to these types:
struct vector3_multiplication_proxy {
  vector3 lhs, rhs;
  operator double() { return 0; /* Your inner product calculation here */ }
  operator vector3() { return {}; /* Your cross product calculation here */ }
};

vector3_multiplication_proxy operator* (const vector3& lhs, const vector3& rhs) {
  return {lhs, rhs};
}

This does have lifetime pitfalls and may delay calculation depending on how you use it, so it may or may not be a good idea. In your particular case, it's probably a bad idea, because the inner and cross products are different things and should probably be denoted by different syntax.


text:
Q: I am trying to compare the local storage value with the index of an array public getCountriesForBKVSVerification(){
    this.blockUserInterface();
  this.authenticationApiService.getCountriesForBKVSVerification().subscribe(success=>{
      this.unblockUserInterface();
      this.countries=success['data'];
      for(let i=0; i<this.countries.length; i++){
   if(localStorage.getItem('countryCode')==this.countries[i['countryCode']){

          this.router.navigate (['login']);
          break;
        } else{
          let type = localStorage.getItem("type")
          if(type == '4'){
            this.redirectUrl = this.prepareRedirectUrlFromLocalStorageForType4({error: true,
            errormessage: 'country code is not of valid format.'});
            const navigationExtras: NavigationExtras = { queryParams: {redirectUrl : this.redirectUrl ,
            errormessage: 'Invalid Wallet Address Attach Request.'} };
            this.router.navigate(['bkvs-verification-error'], navigationExtras);
            return this.redirectUrl;
          }
          this.redirectUrl = this.prepareRedirectUrlFromLocalStorage({error: true,
          errormessage: 'Country code is not of valid format.'});
          const navigationExtras: NavigationExtras = { queryParams: {redirectUrl : this.redirectUrl ,
          errormessage: 'Invalid Social KYC Verfication Request.'} };
          this.router.navigate(['bkvs-verification-error'], navigationExtras);
        }
      }
    }, error=>{
      this.unblockUserInterface();
    })
  }

In this method, I am fetching the list of countries and somewhere I am storing the country code in local storage from some or other URL. So in an if condition I am checking that local storage country code with the index of the country array. It is always comparing with the first index of the country array.
Can anyone assist me with this?

A: this.countries[i['countryCode']

i is the current index in your loop. The above line of code is using i as an array. There is no property countryCode in i as it is a number.
You probably need to do something like:
this.countries[i]['countryCode']

Moreover, as I remember, localstorage works with strings. Be careful with type comparison.


text:
Q: java exception in thread "AWT-EventQueue-0" I have recently installed JDK 1.6 update 43 on my machine .Since then, whenever I try to run the event handling programs, I  encounter a problem, which says Exception in thread "AWT-EventQueue-0"
Which thread does it points to?

A: That's the AWT Event Dispatch Thread (EDT). Code involving AWT or Swing should be run on that thread. This is the thread you'll be on when in you main (running in the "main" thread) you typically call java.awt.EventQueue.invokeLater.

A: Look at your stacktrace. At some point you will find some entry which is from your own code. Maybe a null pointer exception or similar. This is where you must look at.


text:
Q: Apple Watch (WatchKit) layout style library for iOS Layout for Apple Watch is based on placing objects to storyboard. Every new object is placed just under the previous one etc. There is also possible to use groups and align objects same way horizontally. (see details here) I would appreciate to have the same functionality on iOS - to place UIViews this way and define them same attributes like alignment, width relative to container etc. just like in WatchKit.
It is also similar with LinearLayout on Android. I found CSLinearLayoutView on github, but its very old and it doesn't use autolayout.
Does any good library for this purpose exist?
If not.. It looks very easy to implement this by myself, do you see any key problems or limitations which would make it impossible?

A: I don't think there is or will be any addon for the Interface Builder itself, so you could use the same (ugly watchkit) constraints for iOS apps. AutoLayout for iOS is way better and more flexible to use than that WatchKit mess inside IB (Interface Builder of Xcode).
I do prefer to do most of the design work in my code so I don't have to worry if the IB will create some unnecessary stuff for me. If you want some drag and drop, you should use use IB and learn how to use AutoLayout.
The interesting part:
If you want to create your design in code and want some library which is easy to use, you can try on of these: Masonry (Obj-C) or SnapKit (Same Lib but in Swift). Both libs are very strong and up to date. I don't know if the dev implemented a custom alignment to center a subview in its superview. You should check that by yourself. :) If you like the VFL (Visual Format Language), like I do. You should search for a similar Lib or wait until I'm done with my project some day. :D I was inspired by SnapKits shiny syntax and started creating my own framework for VFL constraints. I also implemented the possibility to center my subview in its superview.
    let spacer1 = View(name: "spacer1")
    let spacer2 = View(name: "spacer2")

    let view1 = AutoLayoutView(name: "view1")
    view1.backgroundColor = UIColor.whiteColor()
    view1.layer.cornerRadius = 50

    let view2 = AutoLayoutView(name: "view2")
    view2.backgroundColor = UIColor.redColor()
    view2.layer.cornerRadius = 10

    self.rootView.addSubview(spacer1)
    self.rootView.addSubview(spacer2)
    self.rootView.addSubview(view1)
    self.rootView.addSubview(view2)

    self.rootView.addConstraints { (add) -> Void in
        add.group({ (add) -> Void in
            add.normal.vertical.format("[view1(100)]").alignCenterHorizontaly
            add.normal.vertical.format("[view2(30)]")
            add.normal.horizontal.format("[view1(100)][spacer1]").alignCenterVerticaly
            add.normal.horizontal.format("[spacer1][view2(40)]").alignCenterY
            add.normal.horizontal.format("[view2][spacer2(==spacer1)]|")
        }, identifier: "GroupName")
    }

And with this we we get something like that:

There is still a lot work to do, so I can't public unfinished work yet.
I hope I could help you a little. :)

A: Introduced in iOS 9 as UIStackView - https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/
Custom UIStackView implementation for iOS 7+
https://github.com/oarrabi/OAStackView


text:
Q: Read Registry key and write in textbox the value I have found the following code which reads and writes from the registry.
// Write a value to the registry
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name","Isabella");

// Get value from registry
key.GetValue("Name");
textBox1.Text = key.GetValue("Name"); // error, how can I do?

key.Close();

How would I display the value in a TextBox?

A: Add a call ToString() after ensuring the value isn't null.
object oVal = key.GetValue("Name");
if (null != oVal)
{
   textBox1.Text = oVal.ToString();
}

A: try
textBox1.Text = key.GetValue("Name").ToString();

GetValue returns an object and textbox1.Text wants a string so you need to convert first.


text:
Q: Wait until previous query is complete before running the next one The code below forms part of a websocket that connects to a third party API and receives messages quite frequently from it, currently there are about 3 messages that all appear in very quick succession and I was wondering how I could make sequelize wait until executing one query before the next
this.client.ws.on(WebSocketEvent.ON_MESSAGE, async (message) => {
    if (message.type == 'received') {
        await db.Order.create({
            symbol: message.product_id,
            orderId: message.order_id,
            price: message.funds,
            side: message.side,
            orderedAt: message.time,
            sold: false
        }).catch(err => {
            console.log(err);
            process.exit();
        });
    } else if (message.type == 'match') {
        await db.Order.update({
            volume: message.size
        }, {
            where: {
                orderId: message.taker_order_id
            }
        }).catch(err => {
            console.log(err);
        });
    } else if (message.type == 'done') {
        console.log(message);
        await db.Order.update({
            completeAt: message.time
        }, {
            where: {
                orderId: message.order_id
            }
        }).catch(err => {
            console.log(err);
        });
    }
});

Basically what should happen is a message should come through with the type received and that creates a row in the Order table, a split second later a match message should come through and theoretically it should wait for the previous query to run before updating the previously created order, although this is not the case and the model is not updated.
I've thought about simply adding a delay to the code blocks below the match and done message types but would there be any other way to implement what I am looking for?


text:
Q: How use case scenario should look like, when use case have extensions points or include something I have this simple UC diagram.

Firstly, when the customer enters a repair order, the system checks whether the order can be processed (if the repair company can repair this model of device) - UC "Enter repair order". Only if company can repair this device, customer will start another UC "Select repair type", in the end, depending on which repair type customer will select, it will go to "Enter home address" or "Enter city".
My question is, if I want to build Use Case Scenario for UC "Enter repair order" how should it look like? Should I write in the main course, that customer can enter another use case?
i.e:
MAIN COURSE

*

*Customer login to the webpage.

*Customer fills in an order form.

*System displays information that the company can repair this device.

*Customer enters UC "Select repair type".

*System displays information that the order has been saved.

ALTERNATIVE COURSE

*System displays information that the company cannot repair this device.

*System displays information that the order has not been saved and ends use case.

Or this should be rather:
MAIN COURSE

*

*Customer login to the webpage.

*Customer fills in an order form.

*System displays information that the company can repair this device.

*Customer enters UC "Select repair type" and ends use case.

ALTERNATIVE COURSE

*System displays information that the company cannot repair this device.

*System displays information that the order has not been saved and ends use case.

Does this scenario make sense?

A: The first thing I'd do is throw away the use case diagram. In other answers, I've frequently quoted Martin Fowler, either from his site or his book, UML Distilled, where he expresses the lack of usefulness and value in UML Use Case diagrams. I'd only look at the two textual representations of the use case.
The next step is to clearly define what a use case is. A use case is a definition for how a user interacts with software (or a system) to achieve a useful result, considering inputs and responses to those inputs (or outputs). Based on this definition, the first example of a textual representation of the use case is the better of the two, since the main course actually ends with something valuable happening.
I'm not a fan of the extraction into child use cases, though, at least based on this example. It may make sense to promote reuse of the detailed textual descriptions, but unless the same steps related to "select repair type", "enter home address" and "enter city" are reused in several use cases, I would consider those steps in the "enter repair order" use case. I'd also question why "enter home address" and "enter city" are separate use cases, since a city is a part of an address. It seems like there are more detailed design decisions being made here regarding how the domain is being modeled that wouldn't be appropriate for consideration at the use case level.


text:
Q: How do I make a Python script along with its modules self-contained? programming novice here with a development management question.
I'm writing a very simple Python script in Windows 7 that will be copied into a directory of Excel files sort it all by filename, exclude the scriptfile in the directory, and process them in order.
I've installed both Python 2.7 and 3.4 on my system which resides in C:\Python27 and C:\Python34 respectively.
I've written the sorting part which I'm happy with, but I've had to install the natsort module, which was supposed to be compatible only with 2.7, but was automatically installed by pip into my C:\Python34... directories instead... I must run the script as "C:\Python34\python tvcrunch.py" without getting an ImportError: No module named natsort.
Now I need to install the xlrd and xlwt packages for processing my Excel files, and they installed into C:\Python27... directories despite being compatible with Python 3.2+.
I think by now you all understand the conundrum I'm in. I would like this script to be portable enough so I can drop it onto any computer and have it run without needing to reinstall all these modules and packages. How do I do that? Script below:
import os
from os import listdir
import natsort

somedir = r'.'
fileList = []

def list_files(path):
    for item in os.listdir(path):
        if os.path.isfile(os.path.join(path, item)):
            if item != r'tvcrunch.py':
                fileList.append(item)
    return fileList

list_files(somedir)
natsort.natsorted(fileList, key=lambda y: y.lower())
print(fileList)

A: If you are looking to building a single native windows executable check
http://www.py2exe.org/
Tutorial link: http://www.py2exe.org/index.cgi/Tutorial
Support for Python 3.x https://pypi.python.org/pypi/py2exe/0.9.2.0
"
py2exe is a Python extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.Spice
"


text:
Q: Drawing circle and setting it visible on canvas I have some codes making jFrame and canvas. They are visible. But I don't know how to set a circle visible on the canvas
    package unitcirclevisulaization;

    import java.awt.Canvas;
    import java.awt.Graphics;
    import javax.swing.JFrame;

    public class UnitCircleVisulaization extends Canvas {

        public static void main(String[] args) {
            JFrame frame = new JFrame("Unit Circle");
            Canvas canvas = new Canvas();
            canvas.setSize(800,800);
            frame.add(canvas);
            frame.pack();
            frame.setVisible(true);
        }

        public void paint(Graphics g)
        {
            g.fillOval(400, 400, 400, 400);
        }

    }

I just want a circle to appear on the canvas, and be able to set color of the circle

A: Your paint method is inside the UnitCircleVisulaization class which is never instantiated, so the paint method is never called.
To fix this, just replace the line
Canvas canvas = new Canvas();

with
Canvas canvas = new UnitCircleVisulaization();

This works because UnitCircleVisulaization extends Canvas which contains the paint method.  Then the paint method is automatically called when the frame is made visible.


text:
Q: Generate Signed APK isn't displayed in Android Studio I am on Android Studio 3.6.3 and in order to publish my App to the Playstore, I need to generate a signed APK. As I learned in multiple consultations of the internet, there should be the option in the Menu->Build->generate signed APK. It is not there. Also, I can't change my Build Variants, 'nothing to show' is displayed. I found in an older answer to set my Keystore up in the Project structure section, which is no longer possible, at least for me. So I went to the build.gradle, set up my Keystore, imported the Android-Certificate put all my credentials there. Error in line 58, Could not get unknown property 'meister', was the result.
All options I found to generate this signed APK aren't working for me.
I just don't know how to help me now, other than asking you.
missing option, generate signed APK

A: Build bundle(s) / Apk(s) is disabled in flutter
check the below links may help you
https://flutter.dev/docs/deployment/android
https://medium.com/@psyanite/how-to-sign-and-release-your-flutter-app-ed5e9531c2ac

A: For those who still got this issue when releasing Android Flutter app, I resolved this by:

*

*Right click the Project root folder -> Flutter -> Open Android module in Android Studio.

*Wait for the Gradle syncing

*Voilà!

A: seems like a problem with the IDE. try to rename .androidstudio file(it's usually is c:/users//.androidstudio
then reopen android studio
let me know if it works

A: I'm not sure if this is the recommended method, but I also did not have the generate APK/ app bundle option in Android Studio. What worked for me was to right-click on the Android folder of my project in Android Studio. I selected "Flutter > Open Android module in Android Studio" in a new window. I then could see "Build > Generate APK" in Android Studio.


text:
Q: Time Consuming WCF service call blocks the other WCF service calls. I am using a WCF service with my Silverlight 5 Application.
In one of my service calls I am doing a time consuming job. It takes 1 or 2 minutes to complete the event. I am not blocking the UI with busy indicators, so the user can still interact with the application.
The problem is when I do my first service call, it performs some time consuming operation. When the user loads some other, my second service call is not being processed until the first service is completed.
How can I perform the time consuming service call in separate thread to avoid other
calls waiting for this service completion?
WebService Code
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService
{[OperationContract]
    public bool PerformFileScan(int fileID)
    {
    //Time Consuming Process
    }
}

cs
client.PerformFileScanAsnc(docId);
client.PerformFileScanCompleted += new EventHandler<.PerformFileScanCompletedEventArgs>(client_PerformFileScanCompleted);

A: You have two options:

*

*Make your call asynchronous on the server side. You can use the TPL and just write something like Task.Factory.StartNew(...)

*You can decorate your service implementation with the ServiceBehavior attribute and set the ConcurrencyMode to Multiple:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class YourService
{

}

Then wcf will schedule calls to your service in parallel. But then you have to ensure that your service code is threadsafe!


text:
Q: How to disable bootstrap style I used modal.js from bootstrap, but after hiding a modal my div look likes like it has a blue border:

How do I disable or remove this border in .js/.css

A: Most browsers have a web development tool built in.
Chrome and IE have their own Developer Tools built in however FireFox has Firebug (which you have to install as an extension).
With these tools, you can "inspect" the DOM (Document Object Model) and see how the CSS styles are applied.
Here is a screenshot from Chrome (by clicking on a tag on the left hand side you will see which CSS are applied to it on the right side under "Computed Style" and "Styles"):

In your case you have to traverse down the DOM until you find the div you are looking for and then see which CSS selector is applying the border you want to remove.


text:
Q: How to setup react properly I have been following the react setup instructions on codecademy:
When I type in "npm run build" into the terminal I get this error:

I can't seem to figure out how to get it to work.
Here is the link to my code on my github:
https://github.com/throwkill999/react_demo

A: The error tells you that output.build is not a valid option. You probably meant to use output.path. There are other problems with how you concatenate __dirname in some places, because you need a leading / for them. But it's better to use path.resolve for that.
Your config would look like this:
var path = require('path');
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: path.resolve(__dirname, 'app/index.html'),
    filename: 'index.html',
    inject: 'body'
});

module.exports = {
    entry: path.resolve(__dirname, 'app/index.js'),
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            }
        ]
    },
    output: {
        filename: 'transformed.js',
        path: path.resolve(__dirname, 'build')
    },
    plugins: [HTMLWebpackPluginConfig]
};

Also in ./app/index.js you have a typo, it should be ./components/Apps (you forgot the s).


text:
Q: Selenium Extract the ID of an element found via text in Java I have a set of Cucumber tests I wish to execute using selenium and Chrome. Most of my test work fine. I am currently trying to parametertize one particular step so that anyone using the Test can simply name the elements they want and the test will find them.
The Cucumber test looks something like this:
When I go to the "Inventory" / "Inventory" application

And I search the "Description" field for "a"

I was able to get the when statement to parameterized very easily, but the And Statement is giving me a bit more trouble. The page itself has several sets of tables with a consistent id scheme The xpath for the header with the word "Description" looks like this:
//label[@id='m6a7dfd2f_ttrow_[C:2]_ttitle-lb']

and the input field has this xpath
//td[@id='m6a7dfd2f_tfrow_[C:2]-c']/input

For reference the immediate next input field, located below the label room, has this xpath
//td[@id='m6a7dfd2f_tfrow_[C:3]-c']/input

So each label and input field have the same id scheme and only the number following "c:" seems to change. That number is the same for both the label and it's corresponding input value. I would like to some how scan the page for the word "Description" and extract the ID of the element associated with it and then truncate it down to the number. I already have variables set up to hold the rest and it would hopefully as follows:
@When("^I search the \"([^\"]*)\" field for \"([^\"]*)\"$")
public void i_search_the_field_for(String searchField, String searchItem) throws Throwable {
String baseinputXPath = "//td[@id='m6a7dfd2f_tfrow_[c:";
String endinputXPath = "]-c']/input";
String elementNumber = "The return of some sort of method based on searchField";//TODO
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).clear();
driver.findElement(By.xpath(baseinputXPath + elementNumber + endinputXPath)).sendKeys(searchItem);
driver.findElement(By.id("search_button_img")).click();

If there is a way to pull out that number based only on the description text, that would be super helpful.

A: Use a xpath to search for the WebElement with word 'Description' in a label tag.
"//label[text(),'Description']" or "//label[.='Description']" or "//label[contains(text(),'Description')]"

Use the getAttribute("id") to get the id.


text:
Q: How to connect database from root directory? how to connect database from root folder in winform. I have following code,
Data Source=.\SQLEXPRESS;AttachDbFilename="D:\My Work\Programming\ASP\Projects\Jobapp\App_Data\dtbs.mdf";Integrated Security=True;User Instance=True;

and I want as this,
Data Source=.\SQLEXPRESS;AttachDbFilename="~/dtbs.mdf";Integrated Security=True;User Instance=True;

can anyone tell me??

A: this is the way bros..
   Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|dtbs.mdf;Integrated Security=True;User Instance=True


text:
Q: Mapping out railways from paper? I have a physical copy of a map with railways that I want to import directly into ArcGIS (the network of railways), but I have no data on coordinates of any kind (it's a really old map but the lines are clear to see).
What would be the best way to go about this?
I'm a beginner.

A: You have to scan your paper map and then georeference your file, so that the image is aligned correctly in space in your coordinate system:
http://desktop.arcgis.com/en/arcmap/latest/manage-data/raster-and-images/fundamentals-for-georeferencing-a-raster-dataset.htm
Then you have to create a geodatabase or shapefile (or edit an existing geodatabase/shapefile) and digitize/edit the railways as line features manually.
If you have too many railways to digitize manually maybe ArcScan (an extension) is also useful, but I never tried that.: https://desktop.arcgis.com/en/arcmap/latest/extensions/arcscan/what-is-arcscan-.htm
Digitizing one paper map should be fine manually.


text:
Q: Merging a pull request to my fork I have created a fork of jimson gem repository.
How I can merge this pull request to my fork

A: git pull lets you give a URL for a repository, so you can use something like:
git pull https://github.com/mitfik/jimson.git next


text:
Q: $p$-adic exponential function Simple question about $p$-adic numbers $\mathbb{Q}_p$. How do I evaluate $$\exp(x)=\sum_{n=0}^\infty \frac{x^n}{n!}$$ where $x\in {\mathbb Q}_p$. I'm a bit confused, because as far as I understand it, each term is added in the same way as in $\mathbb R$, so why should the result be different?
As a start let's evaluate $x=1$ in $p=3$.

A: If you want to try $\exp(3)$ in $p=3$, here are the first few partial sums:
$$ \eqalign{1 &= 1\cr
            1 + 3 &= 1 + 3\cr
            1 + 3 + \frac{9}{2} &= 1+3+2 \cdot 3^2+ 3^3+3^4+\ldots\cr
            1 + 3 + \frac{9}{2} + \frac{9}{2} &= 1 + 3 + 3^2\cr
            1+ 3 + \frac{9}{2} + \frac{9}{2} + \dfrac{27}{8} &= 1 + 3 + 3^2 + 2 \cdot 3^3 + 2 \cdot 3^4 + \ldots\cr
            1 +3 + \frac{9}{2} + \frac{9}{2} + \dfrac{27}{8} + \dfrac{81}{40} &=
    1 + 3 + 3^2 + 2 \cdot 3^3  + 0 \cdot 3^4 + \ldots\cr
  1 + 3 + \frac{9}{2} + \frac{9}{2} + \dfrac{27}{8} + \dfrac{81}{40} + \frac{81}{80} &= 1 + 3 + 3^2 + 2 \cdot 3^3  + 2 \cdot 3^4 + \ldots\cr}$$
and it turns out all later terms have numerators with higher powers of $3$ than $3^4$, so the start of the $3$-adic expansion of $\exp(3)$ is
$ 1 + 3 + 3^2 + 2 \cdot 3^3  + 2 \cdot 3^4 + \ldots$.  As was mentioned, this is a $3$-adic number, not the same as the real number $\exp(3)$, nor any other real number.

A: The reals (and complexes) are truly different from the various $p$-adic fields $\Bbb Q_p$. One of the glaring differences is the domain of convergence of exponential and logarithm.
For $\Bbb R$ and $\Bbb C$, the exponential series is convergent for no matter what $z$ you plug into it, while the logarithmic series is convergent only for $|z|<1$.
For any $p$-adic field (including the complete extensions of $\Bbb Q_p$), the logarithmic series is still convergent for $z$ with $|z|<1$, but for convergence of the exponential series, you need the very restrictive condition $|z|<\varepsilon^{\frac1{p-1}}$, where $\varepsilon=|p|$ must be a positive real number $<1$, and $\varepsilon=1/p$ is the conventional choice. The above restriction means that you can calculate the $3$-adic value of $\exp(3)$, as @RobertIsrael has done in his answer, but you can not calculate the $2$-adic exponential of $2$.
Now that I'm on my hobby-horse, I must ride it a bit further. The real logarithm extends from its domain of convergence to a homomorphism from the group $\Bbb R^{>0}$ onto $\Bbb R$, multiplicative group to additive group. The complex logarithm has no such extension: there is no group containing $1+\{z\in\Bbb C:\,|z|<1\}$ on which the logarithm can be defined as a homomorphism.
The $p$-adic logarithm is much more wonderful (and useful) than the complex, for if $k$ is a complete $p$-adic field, the set $1+\{z\in k:\,|z|<1\}$ is a multiplicative group, and the logarithmic series defines a homomorphism from it to the additive group $k$. If you have a $p$-adic number $z$, you could try to define $\exp(z)$ as a number $\zeta$ such that $\log(\zeta)=z$, and this equation is always solvable, for $\zeta$ perhaps in a finite field extension of $\Bbb Q_p$. Only problem is that there are infinitely many such $\zeta$, and in most cases, there is little reason to choose one of these over the others. In my opinion, this is the deep reason why you can't define the exponential of most $p$-adic numbers.


text:
Q: Is my iPad 2 a "Rev A"? After spending some time searching with Google and on developer.apple.com, I still can't figure whether my iPad 2 is a "Rev A" or not (its model is MC979LL/A).
How can I know my exact model?

A: You don't have a Rev A iPad 2 — the MC979 is an iPad2,1 (16 GB White).
The Rev A iPad 2 (iPad2,4 — A1395) model numbers start with MC954 (black) or MC989 (white). They use the Apple A5 Rev A.
Source: The iPhone Wiki — Models
To view your model number, you can find it in Settings → About.


text:
Q: Isolation forest subsampling I have a small dataset which i want to look for anomalies with isolation forest.
In all the papers I read, I see that sub-sampling is an advantage (I'm sure I fully understand why).
Since my data set is small, all data points are picked in the isolation forest training.
Is this a disadvantage?


text:
Q: How to iterate over different variables/states to create an object? I need help iterating over variables/state elements to create an object. I am going to iterate over firstName state, lastName state, and many more states. The code is getting way too complicated. Was wondering if there is a proper way to build an object for a graphql call? or just a better way to build an object?
I have a profile page that has forms for updating the user's account. Each form input has state and setState props. On submit of the form these values need to be checked against the previous queried information stored in the account object stored in state. I am using a graphql endpoint and when I call make the update account call, I have 3 choices for each parameter value in the graphql call For example, firstName can be
1) Null (delete in database)
2) Some non-null value (change to this value in database)
3) field does not exist in call graphql call (do nothing to that attribute)
The code below I have to do for 20 state values which is not practical.
// If there is a difference between client's firstName and queried firstName in server
if (firstName != account.firstName) {
  //If we stored firstName as empty String
  if(firstName === ''){
    //If the firstName queried is not empty
    if(account.firstName != null) {
      //Set the objects first name attribute to null, so server deletes field
      input['firstName'] = null;
    } else {
      //firstName is empty string and server value is null, so do nothing, do not add attribute firstName to object "input"
    }
  } else {
    //firstName is not an empty string so add it to object value
    input['firstName'] = firstName;
  }
}

If there is a better way to do this I would love the help.

A: One way around it is to use the bracket notation to extract specify the key for which you want to extract the value and the value that it needs to be checked against.

function getComputedValue(value, key) {
  if (value != account[key]) {
    if (value === '') {
      if (account[key] != null) {
        input[key] = null;
      } else {

      }
    } else {
      input[key] = value;
    }
  }
}

let firstName = getComputedValue("Tom", "firstName");
let lastName = getComputedValue("Smith", "lastName");

A: There are many ways you can approach this problem. I suggest you use some of the functions Underscore JS provides :
pairs_.pairs(object)
Convert an object into a list of [key, value] pairs. The opposite of object.
_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]

Then you can iterate through the array
_.each(array, function(pair) {
// Insert the input assignment code here for each key
});


text:
Q: call C dll from C# complex structure I have c dll came from outside of our group.
#pragma pack(push, 8)
typedef struct
{
    int int1;
    int int2;
    int int3;
    int int4;
    int int5;
    int int6;

    int int_array1[250];
    int int_array2[250];
    int int_array3[250];
    int int_array4[250];
    int int_array5[250];
    int int_array6[250];
}my_structure
#pragma pack(pop)

extern "C" {

 __declspec(dllexport) void set_my_structure(my_structure mystruct);
 __declspec(dllexport) my_structure get_my_structure();

}

I am using the following code to call the dll from C#.
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public class MyStructure
{
    public int int1;
    public int int2;
    public int int3;
    public int int4;
    public int int5;
    public int int6;

    public int[] int_array1 = new int[250];
    public int[] int_array2  = new int[250];
    public int[] int_array3 = new int[250];
    public int[] int_array4 = new int[250];
    public int[] int_array5 = new int[250];
    public int[] int_array6  = new int[250];
}

[DllImport(_dllName, EntryPoint = "set_my_structure", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern void SetMyStructure(MyStructure data);

[DllImport(_dllName, EntryPoint = "get_my_structure", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern MyStructure GetMyStructure();

However, the code throws exception and stuck in neutral gear when I call GetMyStructure method. What is wrong? What is the best approach to handle this?


text:
Q: Do different Dehn fillings produce homeomorphic 3-manifolds ? Hi, everyone.  I am interested in the dehn filling and Hyperbolic 3-manifold.
Suppose M be an orientable compact 3-manifold with one torus boundary and int(M) admit a
hyperbolic structure.  Thurston proved that almost all the dehn fillings produced
hyperbolic 3-manifolds.
My question is:
Among all the hyperbolic dehn fillings,  is there possible that two different hyperbolic dehn fillings produce same 3-manifold, for some M? Is it true for all the one cusp hyperbolic 3-manifolds?
If the answer to the question is positive, is there an theorem describing this thing?
Any answer and reference are welcome! Thanks!

A: To add even more details to Richard Kent's wonderful answer, the question of cosmetic surgeries showed up as Problem 1.81 on Kirby's list.
Although there are no non-trivial knot complements in $S^3$, that admit non-trivial $S^3$ surgeries the Blieler, Hodgson and Weeks paper that Richard mentions gives knot complements in lens spaces that have this property. In earlier work, Gabai and Berge independently found infinitely many examples of hyperbolic knot complements in $S^1 \times D^2$ that admit at least one (and sometimes two) non-trivial $S^1 \times D^2$ fillings.
A good reference for some recent advances on the cosmetic surgery problem is Yi Ni and Zhongtao Wu's work here. For knots in $S^3$, they are able place some restrictions on what pairs of rational slopes can admit, truly cosmetic (sometimes called purely cosmetic) surgeries.
In particular, they have a succinct statement of the cosmetic surgery conjecture that they attribute to the authors of Kirby's problem list. Namely:
If $M \not\cong S^1 \times D^2$, then for any knot $\gamma \subset M$, $M-\gamma$ does not admit any truly cosmetic fillings.

A: This phenomenon is called "cosmetic surgery."
If $K$ is an amphichiral knot in the $3$--sphere with exterior $M_K$, then $M_K(p/q) \cong - M_K(-p/q)$.  So if $p/q$ is a hyperbolic filling slope, then this is the example you seek.  Note that the homeomorphism is orientation-reversing. If there is an orientation-preserving homeomorphism between $M_k(p/q)$ and $M_K(p'/q')$, the surgeries are called ``truly cosmetic,'' and it is conjectured that cosmetic surgeries on hyperbolic knots are never truly cosmetic.
Take a look at Bleiler, Hodgson, and Weeks, ``Cosmetic surgery on knots,'' in
Proceedings of the Kirbyfest, pp. 23-34 , Geometry
and Topology Monographs, Vol. 2, Coventry, 1999 as a beginning reference, and the conjecture that cosmetic surgeries on hyperbolic knots are never truly cosmetic.
EDIT: Regarding your second question, I'm pretty sure there are hyperbolic manifolds $M$ that admit no cosmetic surgeries at all.  Here's a sketch:
I'll use $\partial M$ to mean a cusp cross section of a $1$-cusped hyperbolic manifold $M$, normalized to be a flat torus of area one.
By a theorem of Nimershiem, the shapes of flat tori appearing as cusp cross sections of 1-cusped $3$-manifolds is dense in the moduli space of tori. (see Nimershiem, ``Isometry classes of flat 2-tori appearing as cusps of hyperbolic 3-manifolds are dense in the moduli space of the torus,'' in Proceedings of Low-Dimensional Topology, 1992, 133-142.)
By Nimershiem's theorem, we may pick an $M$ such that $\partial M$ has a very short curve $\gamma$ and so that the group of isometries of $\partial M$ up to isotopy is trivial.  Let us also assume that $M(\gamma)$ has no short geodesics (you should be able to achieve this by some covering space tricks).
Now, suppose that $M$ admits cosmetic fillings $M(\alpha) \cong M(\beta)$ with $\alpha \neq \beta$.  If $\alpha \neq \gamma$, then $\alpha$ is really long in $\partial M$, and it follows from sharp versions of the Hyperbolic Dehn Filling Theorem due to Hodgson and Kerckhoff that the core of the filling torus is short in $M(\alpha)$.  This means that $\alpha \neq \gamma \neq \beta$.  Furthermore, it means that the cores of the filling tori in $M(\alpha)$ and $M(\beta)$ are the unique short curves in these manifolds, respectively.  So any homeomorphism $M(\alpha) \to M(\beta)$ must preserve these cores (this part of the argument is in lemma 1 of the Bleiler-Hodgson-Weeks paper).  So, the homeomorphism $M(\alpha) \to M(\beta)$ comes from a homeomorphism (and hence an isometry) of $M$, which induces an isometry of $\partial M$ which is not isotopic to the identity (since we assume that $\alpha \neq \beta$).  Since we have chosen $\partial M$ to have no such isometries, we have a contradiction, and must conclude that $M$ has no cosmetic fillings.


text:
Q: How to combine Storybook and jest tests? Background: Many of my auto tests are testing UI components. Every time a test fails it's difficult to debug. It would be very helpful, if the given test input could be rendered, so I can have a look at what is going on.
Storybook provides exactly that feature: Define some input and render the component in that state.
In general, UI auto test cases are often also cases I might also want to check visually at times.
Problem

*

*Test cases are structured hierarchically with describe and test. Stories need to have a flat structure, because they need to export.

*As soon as I add an test('', ()=>{}); to my .stories.tsx file, storyboard stops showing the component (silently, not showing any error).

Question
How can I easily add my test case content (what's inside render) to storybook?


text:
Q: Fetch with rtk query on page reload How to fetch with rtk query only on page reload (React).
I'm trying this, but it fetches even when useData.id is undefined. "skip: !userData.id" doesn't help
import { useGetUserDataQuery } from 'api/agents';

export function MainRouter() {
  const userData = useTypedSelector((state) => state.user);

  useGetUserDataQuery({ id: userData.id }, { skip: !userData.isAuthenticated });

  return (
    <Routes>
      <Route path={APP_ROUTES.MAIN} element={<RequireAuth to={<HomePage />} />} />
      <Route path={APP_ROUTES.SIGN_IN} element={<SignInPage />} />
      <Route path={APP_ROUTES.SIGN_UP} element={<SignUpPage />} />


text:
Q: How can I access custom IdentityUser data (Img Name) inside the LoginPartial (.Net Core 2.2) I was wondering how I can display the custom data I've used to extend the IdentityUser.
By default the loginpartial displays User.Identity.Name (which is actually an e-mail address), I would like to display the user's fullname and display an user image with it. It calls User.Identity.Name from interface IIdentity
    namespace System.Security.Principal
{
    public interface IIdentity
    {
        string AuthenticationType { get; }
        bool IsAuthenticated { get; }
        string Name { get; }
    }
}

I can't change this file though. This is my class extending the identityuser
    public class ApplicationUser : IdentityUser
{
    public ApplicationUser() : base() { }
    public string Voornaam { get; set; }
    public string Tussenvoegsel { get; set; }
    public string Achternaam { get; set; }
    public string Gebruikersnummer { get; set; }
    public string ImgNaam { get; set; }
}

in the partial view I call for this model class aswell:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Now my question is, how can I retreive string ImgNaam inside of my partial view?

A: I think it would be better to store the information you need in Claims (you can read this post about it).
But you also can get information using UserManager.
You can use User variable which has ClaimsPrincipal type to get the whole user from UserManager using the following code:
@
{
     var activeUser = await UserManager.GetUserAsync(User);
}

After this, you can use this variable:

   <img src="@activeUser.ImgNaam">

A: You can do as follows:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@{
   ApplicationUser loggedInUser = await UserManager.GetUserAsync(User); // Here `User` is the claim principal
   var imgNaam= loggedInUser.ImgNaam;
}


text:
Q: ¿Porque el Evento Install y Unistall de la clase Installer no ejecuta ciertos metodos? C# Hola tengo una clase llamata installer1 que hereda de installer y estos son los eventos que tengo definidos
public partial class Installer1 : Installer
{
    Log Log = Log.ObtenerInstancia();
    public Installer1() : base()
    {
        InitializeComponent();
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        try
        {
            MessageBox.Show("Install", "ASDASDASD");
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            rkApp.SetValue("DNS", Application.ExecutablePath.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error",ex.Message);
        }
    }
    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        Log.Escribir("Entro");
        MessageBox.Show("Unistall", "ASDASDASD");
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        rkApp.DeleteValue("DNS");
    }
}

El problema es que solo ejecuta los metodos de MessageBox y todos los demas no los ejecuta, no ejecuta el Log ni ejecuta el RegistryKey, no salen excepciones ni nada, ¿Como puedo hacer que funcionen los metodos correctamente?


text:
Q: How can i pass add-on parameters to hosted page API? I want pass add-on parameters(add-on quantity,code etc ) to hosted page API.Like we're passing quantity of plan.
https://:your_subdomain.recurly.com/subscribe/gold?quantity=5

A: Use some basic steps

*

*Login at recurly with your credential.

*Click on Subscription Plans in left side bar.

*Select your plan and edit

*You will find Create Addon Option here.


text:
Q: How to perform Excel Relative reference formula in Python =IF(AND(C2=C1,A2=A1,F2=F1,K2=K1,LEFT(B2,8)<>LEFT(B1,8)),"same","")

How to perform above excel formula in python? Need to create a loop to perform the formula for the whole column.

A: # cond1 & cond2 Is equivalent to `AND`
# use shift(1) to compare the row and it's previous row
# str[:8] Is equivalent to `LEFT(B2,8)`
#  np.where Is equivalent to `IF`

cond = True
for col in ['C', 'A', 'F', 'K']:
    cond &= df[col] == df[col].shift(1)
cond &= df['B'].str[:8] == df['B'].str[:8].shift(1)

np.where(cond, "same", "")


text:
Q: Flutter Text To Speech: Speak several strings subsequently with different SpeechRates I have a problem with the Flutter Text To Speech package.
When clicking on a FloatingActionButton I would like to speak/play several Strings (with different Speechrates) subsequently. However, when doing so, I can only hear the last string that I have passed onto the function and not the first one.
As you can see in the code below, I have tried to make use of the asynchronus programming (async / await).
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_tts/flutter_tts.dart';

class SpeakerClass extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
  // TODO: implement createState
  return _SpeakerClassState();
  }
}

class _SpeakerClassState extends State<SpeakerClass>{
  String text1 = 'eins';
  String text2 = 'zwei';
  String text3 = 'drei';
  String text4 = 'vier';
  String currentTtsString;
  double ttsSpeechRate1 = 0.5;
  double ttsSpeechRate2 = 1.0;
  double currentSpeechRate;

  Future playTtsString1() async {
    currentTtsString = text1;
    currentSpeechRate = ttsSpeechRate1;
    await runTextToSpeech(currentTtsString, currentSpeechRate);
    return null;
  }

  Future playTtsString2() async {
    currentTtsString = text2;
    currentSpeechRate = ttsSpeechRate2;
    await runTextToSpeech(currentTtsString, currentSpeechRate);
    return null;
  }

  @override
  Widget build(BuildContext context) {
  return Scaffold(
    body: FloatingActionButton (
      backgroundColor: Colors.blue,
      child: Icon(Icons.volume_up, color: Colors.white),
      onPressed: () async {
        await playTtsString1();
        await playTtsString2();
      },
    )
  );
  }

}

Future<void> runTextToSpeech(String currentTtsString, double currentSpeechRate) async {
  FlutterTts flutterTts;
  flutterTts = new FlutterTts();
  await flutterTts.setLanguage("en-GB");
  await flutterTts.setVolume(1.0);
  await flutterTts.setPitch(1.0);
  await flutterTts.isLanguageAvailable("en-GB");
  await flutterTts.setSpeechRate(currentSpeechRate);
  await flutterTts.speak(currentTtsString);
}

When pressing the FloatingActionButton I expect the program to first carry out the function playTtsString1 ("eins" with a speed of 0.5) and afterwards the function playTtsString2 ("zwei" with a speed of 1).
However, somehow I can only hear the program saying "zwei". I guess the program is not waiting for the first function "playTtsString1" to be finished and already carries out the second function "playTtsString2". I would really appreciate any help on this matter!

A: import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_tts/flutter_tts.dart';

class SpeakerClass extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
  // TODO: implement createState
  return _SpeakerClassState();
  }
}

class _SpeakerClassState extends State<SpeakerClass>{
  String text1 = 'eins';
  String text2 = 'zwei';
  String text3 = 'drei';
  String text4 = 'vier';
  String currentTtsString;
  double ttsSpeechRate1 = 0.5;
  double ttsSpeechRate2 = 1.0;
  double currentSpeechRate;

  FlutterTts flutterTts;
  bool bolSpeaking = false;

  Future playTtsString1() async {
    bolSpeaking = true;
    currentTtsString = text1;
    currentSpeechRate = ttsSpeechRate1;
    await runTextToSpeech(currentTtsString, currentSpeechRate);
    return null;
  }

  Future playTtsString2() async {
    bolSpeaking = true;
    currentTtsString = text2;
    currentSpeechRate = ttsSpeechRate2;
    await runTextToSpeech(currentTtsString, currentSpeechRate);
    return null;
  }

  @override
  Widget build(BuildContext context) {
  return Scaffold(
    body: FloatingActionButton (
      backgroundColor: Colors.blue,
      child: Icon(Icons.volume_up, color: Colors.white),
      onPressed: () async {
        // Play String 1
        await playTtsString1();

        // Check String 1 Finish
        new Future.delayed(new Duration(milliseconds: 100), () async {
            // loop until bolSpeaking = false
            while (bolSpeaking) {
              await Thread.sleep(100);
            }

            // play String 2
            await playTtsString2();
        }
      },
    )
  );
  }
}

Future<void> runTextToSpeech(String currentTtsString, double currentSpeechRate) async {
  flutterTts = new FlutterTts();
  await flutterTts.setLanguage("en-GB");
  await flutterTts.setVolume(1.0);
  await flutterTts.setPitch(1.0);
  await flutterTts.isLanguageAvailable("en-GB");
  await flutterTts.setSpeechRate(currentSpeechRate);

  flutterTts.setCompletionHandler(() {
    setState(() {
      // The following code(s) will be called when the TTS finishes speaking
      bolSpeaking = false;
    });
  });

  flutterTts.speak(currentTtsString);
}

A: This should now work with the latest flutter_tts version.
You simply need to set awaitSpeakCompletion before the speaking happens.
You can update your run method like so:
Future<void> runTextToSpeech(String currentTtsString, double currentSpeechRate) async {
  FlutterTts flutterTts;
  flutterTts = new FlutterTts();
  await flutterTts.awaitSpeakCompletion(true);
  await flutterTts.setLanguage("en-GB");
  await flutterTts.setVolume(1.0);
  await flutterTts.setPitch(1.0);
  await flutterTts.isLanguageAvailable("en-GB");
  await flutterTts.setSpeechRate(currentSpeechRate);
  await flutterTts.speak(currentTtsString);
}


text:
Q: tar cvf or tar -cvf ? I have learned to use tar without '-' for options, like tar cvfz dir.tar.gz Directory/ but I recently came accross the slightly different tar -czvf syntax (I think the 'f' must be the last option in this case).
Both work on linux and Mac OS. Is there a recommended syntax, with ou without '-' which is more portable accross unix flavors ?

A: tar is one of those ancient commands from the days when option syntax hadn't been standardized. Because all useful invocations of tar require specifying an operation before providing any file name, most tar implementations interpret their first argument as an option even if it doesn't begin with a -. Most current implementations accept a -; the only exception that I'm aware of is Minix.
Older versions of POSIX and Single Unix included a tar command with no - before the operation specifier. Single Unix v2 had both traditional archivers cpio and tar, but very few flags could be standardized because existing implementations were too different, so the standards introduced a new command, pax, which is the only standard archiver in since Single Unix v3. If you want standard compliance, use pax, but beware that many Linux distributions don't include it in their base installation, and there's no pax in Minix. If you want portability in practice, use tar cf filename.tar.

A: There have been few programs on UNIX that do not follow the current option standard.
One is dd, but dd was derived from the IBM mainframe program DDR (Disk Dump and Restore).
One is ar and the other is tar. From my information, tar wanted to be similar to ar.
All tar implementations work without the - and no useful implementation requires the -. So if you like to write portable scripts, check the SUSv2 standard and only use a commandline that is compatible to SUSv2.

A: I may be a dinosaur, but I think that habitually using cvf instead of -cvf is probably more portable.  I imagine most Linux distros use GNU tar, and I would guess that the *BSDs do also, but you'll find proprietary Unixes that still use the old SysV tar, which used to require you to not use a - in the options.
I do not use -cvf (or -xf or whatever) and I have no trouble even with bleeding edge Arch linux.
And just as a side note, I think you can use the Sun-standard jar command options with or without a - as well.


text:
Q: How can I add a  section to a marionette collectionview with tagName: 'table'? I have a collection view that looks something like this:
var PersonView = Marionette.ItemView.extend({
        tagName: 'tr',
        template: function (model) {
            return _.template("<%= data.firstName %>	<%= data.lastName %>	", {
                firstName: model.firstName,
                lastName: model.lastName
            }, { variable: 'data' });
        }
    }),
    PersonCollectionView = Marionette.CollectionView.extend({
        tagName: 'table',
        itemView: PersonView
    });

It works fine, but I can't figure out the best way to add a
 section to my table. I thought of changing tagName: 'table' to tagName: 'tbody' and adding the thead section in the layout which displays the collection view, but it doesn't look like a very clean approach. Indeed, if I were to use my collection view elsewhere, I would have to reproduce the thead section in another layout... What is the proposed way of doing this?
P.S See https://github.com/shawninder/table-collection-views for a working example. You'll notice the table has no
 section, which is what I'm trying to solve.
UPDATE: Fixed with this commit based on accepted answer

A: You may need to use the CompositeView instead. With CompositeView you can provide a template which adds your thead and use the ItemViewContainer to render you collections. Read the doc and I am sure you will figure out the solution.


text:
Q: (PowerBI) For each column in my table, how do I calculate the number of blank cells and cells with data? I have a large list of client data that I am interested in measuring the number of blanks and the number of cells with data (similar to using the counta and countblank functions in Excel). I'd like the data to be displayed in a table similar to the one pasted below.
Desired Output
[
Sample Data (first 4 rows)

A: You can use the COUNTBLANKS DAX function.
Your DAX will be something like
Measure Name = COUNTBLANKS(tablename[columnname])

For counts of items that are not blank, then you need to COUNTA function, this will count all non empty cells
Measure Name = COUNTA(tablename[columnname])


text:
Q: Transform a DataFrame to a second based DataFrame I want to transform a DataFrame with a start and endtime in a column to a row-wise approach, so that each second, of each time range (starttime, endtime) is present in a second-based view.
The columns value1 and value2 should also be in the final result.
My DataFrame looks like:
starttime                    endtime                   value1        value2
2021-12-15 08:35:28          2021-12-15 12:35:38          2.0           1.0
2021-12-15 12:35:39          2021-12-15 12:49:42          5.0           0.0
2021-12-15 12:49:43          2021-12-15 12:50:35          2.0           3.0
2021-12-15 12:50:36          2021-12-15 12:22:45          1.0           0.0
2021-12-15 12:22:46          2021-12-15 12:22:56          2.0           9.0
...                          ...                          ...           ...
2022-04-12 23:29:01          2022-04-12 23:29:22          2.0           5.0
2022-04-12 23:29:23          2022-04-12 23:29:28          2.0           1.0

And the result should lool like:
2020-12-15 10:35:28     2.0     1.0
2020-12-15 10:35:29     2.0     1.0
2020-12-15 10:35:30     2.0     1.0
2020-12-15 10:35:31     2.0     1.0
...                     ...     ...
2020-12-15 10:35:38     5.0     1.0
2020-12-15 10:35:39     5.0     0.0
2020-12-15 10:35:40     5.0     0.0
2020-12-15 10:35:41     5.0     0.0
2020-12-15 10:35:42     5.0     0.0
...                     ...     ...
2022-04-12 23:29:28     2.0     1.0

My first approach is quite slow and does only work with one value column (and not with different numbers of value columns):
dfs = []
    for row in df.values:
        # Test if the start time smaller than the endtime
        if row[0] <= row[1]:
            timespan = pd.date_range(row[0], row[1], freq='s')
            values = np.repeat(row[column_index], timespan.size)
        dfs.append(pd.DataFrame({"timeframe": timespan, column_name: values}))
    large_df = pd.concat(dfs).drop_duplicates(subset='timeframe', keep='last')


text:
Q: Get docstring of present code portion with Jupyter notebook One of the disadvantages of Jupyter / iPython over Pycharm or Spyder is that I cannot see the documentation of the present code fragment / class / command by default (i.e.: that the referring docstring / signature is not shown automatically).
Is there any plugin / workaround possible to achieve this in a Jupyter notebook as well?

A: Execute a method with ? and the bottom pane will show up.
Inside the parenthesis of a method use shift + tab to bring up documentation pop-up.


text:
Q: Feature extraction and classification in digital image processing techniques I am currently working on a project for the classification of lungs as cancerous or normal depending on the existence of nodules in CT images , such that if there exists a nodule  the MATLAB detects this input case as a cancerous case , otherwise MATLAB detect this case as a normal one. Currently i have successfully developed a technique that can extract any nodule ( if exists ) in the lungs and if there is no  nodule matlab will extract some noise ( bronchi ), which does not have any rounded shape like any nodule. Now can anyone please suggests sources for learning feature extraction using MATLAB and also sources for learning Artificial neural network ( theoretically and also using Matlab ) for classification ? I am looking forward to extract features such as geometrical features ( shape , area , perimeter ) and features such as contrast. Thanks in advance.

A: i'd start with these:
https://it.mathworks.com/products/computer-vision/features.html#deep-learning
https://it.mathworks.com/products/computer-vision/features.html#object-detection-and-recognition
there are lots of ready-to-be used tools that might be useful, i'd look at them before starting writing something new.


text:
Q: Facebook connect log out still showing user I am using the following code and it's v strange - when i log out, if i try to actually go back into facebook i cannot but my code below does not register that i'm logged out and will show my facebook user id still
include '/home/php_/lib/fb_libs/facebook.php';

$facebook = new Facebook(array(
  'appId'  => '123456789',
  'secret' => 'abcdefghilk',
  'cookie' => true
));

$user = $facebook->getUser();

echo "user id is $user";

if ($user){

    try { $user_profile = $facebook->api('/me'); }

    catch (FacebookApiException $e) { echo $e->getMessage(); }
}

if ($user)
{
    $logoutURL = $facebook->getLogoutURL();
    echo "Log out ";
}

else
{
    $loginURL = $facebook->getLoginURL(array(
        'scope' => 'publish_stream,read_friendslists'
    ));
    echo "Log in ";
}

I understand there are other methods e.g. FB.getLoginStatus() so this is not a duplicate question but why, when this is on github facebook SDK, does it not work?

A: I think your cookie is causing the problem try not setting the cookie.


text:
Q: building models with foreignkey and OnetoOne relationship in Django? I am trying to make models for my project.
1) This includes a model for CarInfo, which holds details about the car, such as year, make and model.
class CarInfo(models.Model):
    year = models.IntegerField(blank=True, null=True)
    make=models.OneToOneField('Manufacturer')

2) for the car make, I am thinking of the following model;
class Manufacturer(models.Model):
    CARMAKER_CHOICES=(('Toyota','TOYOTA'),
                    ('ford','FORD'),
                    ('mazda','MAZDA'), ('Honda','HONDA'), )
    carmaker=models.CharField(max_length=20,choices=CARMAKER_CHOICES)

3) for the car model, I want to make the following model, but I do not know how to implement it.
class CarModel(models.Model):
    maker=models.ForeignKey(Manufacturer)
    # if the manufacturerer is Toyota, the different models are
    MODEL_CHOICES=(('Prius','PRIUS'),
                    ('Camry','CAMRY'),
                    ('Rav4','RAV4'),)
    carmodel=models.CharField(max_length=20,choices=MODEL_CHOICES)

As you can see the CarModel is dependent on the manufacturer and hence car model choices will be entirely different. How should I build a model in this case or I am open to better alternative models.

A: Django alone cannot conditionally display/use choices based on another. Probably the easiest approach would be to use Javascript/jQuery on your page to display the choices based on previous selection.
Alternatively, you could also look at using Django's form wizard to show the form at multiple stages.
Either way, this will have to be done at the form/template level and not in the model itself.
UPDATE
There's no way to dynamically populate fields/attributes based on another field in the current model. Additionally, the car models that correspond to their manufacturers will have to be stored somewhere. Currently in MODEL_CHOICES, but as you've explained you want this to be populated based on the manufacturer plus it might become a hassle to keep updating tuples going forward so it's best put in the database.
So if we changed the CarModel and CarInfo models slightly,
class CarModel(models.Model):
    carmaker = models.ForeignKey(Manufacturer)
    carmodel = models.CharField(max_length=20)

class CarInfo(models.Model):
    year = models.IntegerField(blank=True, null=True)
    make = models.OneToOneField('Manufacturer')
    model = models.CharField(max_length=20)

it could hold that information for us like so:
+-----+------------+------------+
| id  |  carmaker  |  carmodel  |
+-----+------------+------------+
|  1  |   Toyota   |   Prius    |
|  2  |   Toyota   |   Camry    |
...

Then if we ever need to filter/restrict the models to their manufacturers via CarInfo, say in a form, it can be done so with a simple query:
class CarInfoForm(forms.ModelForm):
    class Meta:
        model = CarInfo

    def __init__(self, *args, **kwargs):
        super(CarInfoForm, self).__init__(*args, **kwargs)
        self.fields['model'] = forms.ModelChoiceField(queryset=CarModel.objects.filter(carmodel=self.instance.carmodel))

Again, this would be much simpler to do via Javascript or jQuery in the template/browser. If you are not opposed to using third-party libraries there are some that add functionality around models as choice fields: dj-choices, django-smart-select and this django snippet were a few I found.


text:
Q: Вывод lambda функции, в виде текста Приветствую! Знатоки выручайте, долгое время уже пытаюсь разобраться с этим вопросом и никак не могу найти информацию, а точнее нашел, но не то.
Вообщем сама задача.
Есть массив, который содержит в себе lambda функции:
$functs = ['name' => function() {
    return 1;
}];

Мне нужно создать для него редактирование, казалось бы все так просто, взять циклом пробежаться и всунуть все в input и textarea поля.
Но возникла проблема сами функции они не выводятся так как нужно.
А нужно чтобы они также выводились как определены в массиве, то есть строкой.
function() {
    return 1;
}

Прям точно также - как и определены в значении массива.
Пробовал делать так:
$func= new ReflectionFunction($functs['name']);
var_dump($func->__toString());

Но! Выводится мусор, не то, что нужно:
Closure [ <user> function {closure} ] {
  @@ .....\index.php 11 - 13
}

Уже какой день бьюсь в этом направлении и никак не могу решить задачу, чтобы было ключ массива в input, а значение в textarea.
То есть вот так:

Пожалуйста помогите или пните в правильном направлении.
UPD:
Массив может быть любого вида:
Хоть такой:
$functs = ['name' => function() {return 1;},'m'=>fucntion() {}];

В одну строку.
Пробовал решить так:
function closure(Closure $closure) {
    $function = new ReflectionFunction($closure);
    $file = file($function->getFileName());
    for ($i = $function->getStartLine() - 1; $i < $function->getEndLine(); $i++) {
        $str .= $file[$i];
    }
    $funct = mb_substr($str, mb_stripos($str, 'function', 0, 'utf-8'), -1, 'utf-8');
    $funct = mb_substr($funct, 0, mb_strripos($funct, '}', 0, 'utf-8')+1, 'utf-8');
    return $funct;
}

Работает, но только если размер массива 1.
То есть такой:
$functs = ['name' => function() {return 1;}];

а в случае:
(new MyClosure($closure))->__toString();
возникает LogicException, что не совсем гуд, исключено, чтобы это было.
нужно решение, чтобы в любом написании массива с lambda функциями.
Кстате, ссылка с приведенным алгоритмом, не пашет тоже.
Незнаю, как поправить свою функцию, так, чтобы отследить правильную позицию завершения блока функции " } ", а не искать конец " } ", а то получается, что он захватывает все и получается хрень.
Похоже и длину строки надо считать и т.д., формула нужна, как верно отследить.
Выручайте, не врублюсь, какое условие написать?

A: Вот примерчик:
class ClosureDump
{
        const SPLITTERS = PHP_EOL . ', ';

        protected $closure;

        protected $begin;
        protected $end;
        protected $file;

        function __construct(\Closure $closure)
        {
            $this->closure = new \ReflectionFunction($closure);
        }

        function __toString()
        {
            $prepared_ary = $this->prepare();
            $dump_ary = explode('=>', $this->trim(array_shift($prepared_ary)));
            $function_ary = array_slice($dump_ary, 1);
            return $this->trim(array_shift($function_ary));
        }

        protected function trim($string)
        {
            return trim($string, self::SPLITTERS);
        }

        protected function prepare()
        {
            $this->file = $this->closure->getFileName();
            $this->begin =  $this->closure->getStartLine() - 1;
            $this->end =  $this->closure->getEndLine();

            return array_slice(file($this->file),
                $this->begin, $this->end - $this->begin);
        }
}

Входные данные:
$functions = [
    'foo' => function() { return 'foo'; },
    'bar' => function() { return 'bar'; },
];

Ну и результат:
echo new ClosureDump($functions['foo']); // => function() { return 'foo'; }

UPD:
Чуть позже нашел более полноценную реализацию.
UPD2:
class MyClosure
{
    const EOL = PHP_EOL;
    const TAB =  '  ';

    protected $reflection;
    protected $closure;

    # interface

    public function __construct(\Closure $closure)
    {
        $this->setClosure($closure);
    }

    public function getClosure()
    {
        return $this->closure;
    }

    public function setClosure(\Closure $closure)
    {
        $this->closure = $closure;
        $this->reflection = new \ReflectionFunction($closure);
    }

    public function __toString()
    {
        return $this->buildSignature() .
            $this->buildBody() .
            $this->buildTail();
    }

    # protected

    protected function buildSignature()
    {
        $params = [];

        foreach($this->reflection->getParameters() as $param) {

            $str = '';

            if ($param->isArray()) {
                $str .= 'array ';
            } else if ($param->getClass()) {
                $str .= $param->getClass()->name . ' ';
            }

            if ($param->isPassedByReference()){
                $str .= '&';
            }

            $str .= '$' . $param->name;
            if ($param->isOptional()) {
                $str .= ' = ' . var_export($param->getDefaultValue(), true);
            }

            $params[] = $str;
        }

        $ary = ['function (', implode(', ', $params), ') {' . self::EOL];

        return implode($ary);
    }

    protected function buildBody()
    {
        $reflection = $this->reflection;

        $path = $reflection->getFileName();
        $begin = $reflection->getStartLine();
        $end = $reflection->getEndLine() - 1;

        if ($end > $begin) {
            $ary = array_slice(file($path), $begin, $end - $begin);
        } else {
            throw new \LogicException;
        }

        return implode(array_map(function ($line) {
            return self::TAB . trim($line) . self::EOL;
        }, $ary));
    }

    protected function buildTail()
    {
        return '}';
    }
}

$ary = [
    'foo' => function() {
        return 'foo';
     },
    'bar' => function($foo, $bar, & $baz) {
        $baz = $foo . $bar;
        return $baz;
    },
];

$closure = new myClosure($ary['bar']);

Результат вывода $closure:
function ($foo, $bar, &$baz) {
   $baz = $foo . $bar;
   return $baz;
}

После небольшого рефакторинга...

A: Все ребят всем спасибо, разабрался, теперь работает как надо добавил метод:
private function arr(array $array) {
    if(sizeof($array)) {
        $arr = array();
        foreach($array as $key => $value) {
            if(is_callable($value)) {
                $value = new MyClosure($value);
                $value = $value->__toString();
                $arr[] = "'{$key}' => {$value}";
            }
        }
        return'array(' . join(',', $arr) . ');';
    }
    return false;
}

И заработало, меняется туда сюда, скрипт-код и сервер по прежнему живет и видно как добавляем и изменяем, Огромнейшее спасибо, без вас бы я не справился ;)

A: Пришлось делать запись данных уже в нужном виде (если посоветуете, что-то, лучше, буду рад):
public final function arrayDump(array $array): string {
    if (1 <= sizeof($array)) {
        $arr = [];
        foreach ($array as $key => $value) {
            $key = addslashes($key);
            if (is_callable($value)) {
                $value = $this->closure($value);
                $arr[] = "'{$key}' => {$value}";
            } else if (is_string($value)) {
                $arr[] = "'{$key}' => '" . addslashes($value) . "'";
            } else if (is_float($value) || is_double($value)) {
                $value = (double) $value;
                $arr[] = "'{$key}' => {$value}";
            } else if (is_int($value)) {
                $value = (int) $value;
                $arr[] = "'{$key}' => {$value}";
            } else if (is_object($value)) {
                $arr[] = "'{$key}' => '" . serialize($value) . "'";
            }
        }
        return"[\n\t" . join("\t", $arr) . "\n];";
    }
    return'';
}

Ну и сам метод closure
public final function closure(Closure $closure): string {
    $func = 'function(';
    $function = new ReflectionFunction($closure);
    $params = [];
    $parameters = $function->getParameters();
    foreach ($parameters as $param) {
        $string = '';
        if ($param->isArray()) {
            $string .= 'array ';
        } else if ($param->getClass()) {
            $string .= $param->getClass()->name . ' ';
        }
        if ($param->isPassedByReference()) {
            $string .= '&';
        }
        $string .= '$' . $param->name;
        if ($param->isOptional()) {
            $string .= ' = ' . var_export($param->getDefaultValue(), true);
        }
        $params[] = $string;
    }
    unset($parameters, $param);
    $func .= join(', ', $params) . ') {' . PHP_EOL;
    $lines = file($function->getFileName());
    $start = $function->getStartLine();
    $end = $function->getEndLine();
    for ($l = $start; $l < $end; ++$l) {
        $func .= $lines[$l];
    }
    return $func;
}

Теперь нормально работает.

A: Редактирование норм, но сохранение теперь кривится, сохраняя вида:
array(
   'foo'=>
   MyClosure::__set_state(array(
       'reflection'=>
      ReflectionFunction::__set_state(array(
          'name'=>'{closure}',
      )),
       'closure'=>
      Closure::__set_state(array(
      )),
   ))
);

Затем при импорте и обращении к функции вылетает крит:
Fatal error: Call to undefined method MyClosure::__set_state() in ...
Нужно, чтобы массив имел вид:
array(
   'foo'=>function() {
        return 'foo';
     },
);

Видимо это так var_export влияет, есть мысли как его обратно записать в файл массив? Вида:
foo.php:
return array(
  'foo'=>function() {
      return 'foo';
  },
);

Конечно можно попробовать дописать костыль, аналог var_export, но может есть другой выход?