text:
Q: Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'. duplicate entry I'm working on Android Studio 1.5 and my gradle is the following:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 14
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.beatzplayer"
        minSdkVersion 14
        targetSdkVersion 14
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }

        debug {
            minifyEnabled false
        }
    }
}

dependencies {
    compile files('libs/jl1.0.1.jar')
    compile files('libs/JLayer1.0.1.jar')
    compile files('libs/mp3spi1.9.4.jar')
    compile files('libs/tritonus_share.jar')
}

I've sync, cleaned and rebuilt the Gradle but when I tried to run the app after choosing the device the app gave me this error:
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: javazoom/jl/converter/Converter$PrintWriterProgressListener.class

After that, I read Error after adding play-services library : ':app:transformClassesWithJarMergingForDebug' so I add the following code:
compile('libs/JLayer1.0.1.jar') {
    exclude module: 'converter'
}

When I sync again the gradle it reported me this one:
Error:(29, 0) Gradle DSL method not found: 'exclude()'

A: I thing as error say you have one jar file with different name having same classes
 compile files('libs/jl1.0.1.jar')
compile files('libs/JLayer1.0.1.jar')

Both are same if one is not need delete that than build gradel
 once again


text:
Q: option not getting selected automatically I am writing a sell script to automate some steps for server , first i have to switch user then server gives me areas to select then i have to select 1 for  area and then i have to run a  perl program lmsyscon which give me four option then i have to select 3 . then it again gives me 2 option and i have to select 2nd by deafult .here is my script
su poletst -c ". /try/lamtst/.profile Test"
expect -c 'spawn lmsyscon; send 3\r"; interact'
expect -c 'send "1\r"; interact'

the problem is last line is not executing and it is not selecting 2 by default

A: Hmm... This is too complicated. Besides, your su command has no effect on following expect invocations (those are run as your current user).
Instead, create an expect script that does all 3 steps: changes the user and runs stuff. This is easier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Test a function that updates a value I would like to test this function that only updates a Boolean variable. But when I test with toHaveBeenCalled method it passes because the function has been called. However when I read the value of the variable it never updates even though the function was successfully called.
See the code below for more details, the first portion is the main method and the second is the test.
// Main Code.
variableToUpdate: boolean = false;
updateVariable(){
  this.variableToUpdate = true;
}

// Passing Test
it('should call the function', () => {
  spyOn(component, 'updateVariable');
  component.updateVariable();
  expect(component.updateVariable).toHaveBeenCalled();
});

// Failing Test
it('should update the value of the variable', () => {
  spyOn(component, 'updateVariable');
  component.updateVariable();
  expect(component.variableToUpdate).toEqual(true);
});

A: In your second test remove this line:
spyOn(component, 'updateVariable');
to look like this:
  it('should update the value of the variable', () => {
    component.updateVariable();
    expect(component.variableToUpdate).toEqual(true);
  });

spyOn will not call your original implementation, to achieve that you need to do this:
spyOn(obj, 'method').and.callThrough();

Whole test case with spyOn:
it('should update the value of the variable', () => {
    spyOn(component, 'updateVariable').and.callThrough();
    component.updateVariable();
    expect(component.variableToUpdate).toEqual(true);
});


text:
Q: Struggling to understand groupby pandas I'm struggling to understand how the parameters for df.groupby works. I have the following code:
df = pd.read_sql(query_cnxn)
codegroup = df.groupby(['CODE'])

I then attempt a for loop as follows:
for code in codegroup:
    dfsize = codegroup.size()
    dfmax = codegroup['ID'].max()
    dfmin = codegroup['ID'].min()
    result = ((dfmax-dfmin)-dfsize)

    if result == 1:
        df2 = df2.append(itn)
    else:
        df3 = df3.append(itn)

I'm trying to iterate over each unique code. Does the for loop understand that i'm trying to loop through each code based on the above? Thank you in advance.

A: Pandas groupby returns an iterator that emits the key of the iterating group and group df as a tuple. You can perform your max and min operation on the group as:
In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, 0, 0, 1, 1, 1], 'b': [3, 4, 5, 6, 7, 8]})

In [3]: for k, g in df.groupby('a'):
   ...:     print(g['b'].max())
   ...:
5
8

You can also get the min-max directly as df using agg:
In [4]: df.groupby('a')['b'].agg(['max', 'min'])
Out[4]:
   max  min
a
0    5    3
1    8    6


text:
Q: Probability that a set is a subset of another set and limits of probabilities Let $\{A_n\}, \{B_n\}$ be two sequences of infinitely many finite sets $A_n, B_n$ satisfying
$$
\lim_{n \to \infty} \mathbb{P}(a \in B_n \ \mid \ a \in A_n) = 1,
$$
where, for each $n$, the element $a \in A_n$ is chosen uniformly at random.
Is it true that
$$
\lim_{n \to \infty} \mathbb{P}(A_n \subseteq B_n) = 1?
$$
If so, what is a rigours proof?
Intuitively this seems to be true to me; also since
$$
\mathbb{P}(a \in B_n \ \mid \ a \in A_n) = \dfrac{\mathbb{P}(a \in A_n \cap B_n)}{\mathbb{P}(a \in A_n)} = \dfrac{|A_n \cap B_n|}{|A_n|}.
$$
Thank you.


text:
Q: writing shapes and strokes in files I developing a program in WPF and need to write and read shapse(rectangle,ellipse,...) in file and read them.
is there any way for that or i must write its specification like width, height, ... an load them?
any idea?
i used from:
  Stream stream = File.Open("mehdi.txt", FileMode.Create);
            BinaryFormatter bFormatter = new BinaryFormatter();
            ArrayList a = new ArrayList();
            a.Add(shapelist);  //shapelist is arraylist

            bFormatter.Serialize(stream, a);
            stream.Close();

but this code has following error:
Type 'System.Windows.Shapes.Rectangle' in Assembly 'PresentationFramework, Version=4.0.0.0,
 Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

A: You can keep the XAML (Rectangle, Ellipse, etc) that describes your "designs" as separate .xaml files.
Then you can load/save that XAML on demand using XAMLReader.Load/Save.
This will create an object which you can then set as the Content/add wherever you would like it to show up in your UI.

*

*http://www.codeproject.com/Articles/115108/Lazy-Load-XAML-content-from-External-File-and-Vice

*http://www.abhisheksur.com/2010/10/lazy-load-xaml-content-from-external.html

A: this worked!
 FileStream f = new FileStream("mehdi.txt", FileMode.Create, FileAccess.Write); //
        XamlWriter.Save(inkcanvas, f);
        foreach (var e1 in inkcanvas.Children) //
        XamlWriter.Save(e1);
        foreach (var e1 in inkcanvas.Strokes)
               XamlWriter.Save(e1);


text:
Q: How to scale with radius attribute I would like to style vector data based on an attribute (radius). The actual unit is in nautical miles. I don't want to use size-scale field or buffer to style the point rather I would like to make sure that the actual circle created would be drawn to scale based on its attribute.
LONGITUDE,LATITUDE,WIND,PRESSURE,CATEGORY,DATE,RADIUS(m)
145.9,6.5,55,985,4,11/5/2013 0:00,101860
144.6,6.5,60,980,4,11/5/2013 6:00,111120
142.9,6.9,65,975,5,11/5/2013 12:00,120380
141.3,7.1,75,965,5,11/5/2013 18:00,138900
139.7,7.3,85,950,5,11/6/2013 0:00,157420
138,7.6,95,930,5,11/6/2013 6:00,175940
136.2,7.9,105,920,5,11/6/2013 12:00,194460
134.4,8.2,115,905,5,11/6/2013 18:00,212980
132.8,8.7,115,905,5,11/7/2013 0:00,212980
131.1,9.3,115,905,5,11/7/2013 6:00,212980
129.1,10.2,125,895,5,11/7/2013 12:00,231500
126.9,10.6,125,895,5,11/7/2013 18:00,231500
124.8,11,110,910,5,11/8/2013 0:00,203720
122.5,11.4,90,940,5,11/8/2013 6:00,166680
120.5,11.9,90,940,5,11/8/2013 12:00,166680
118,12.2,90,940,5,11/8/2013 18:00,166680
116.6,12.3,90,940,5,11/9/2013 0:00,166680
114.8,13.5,90,940,5,11/9/2013 6:00,166680
113.1,14.4,85,945,5,11/9/2013 12:00,157420
111.4,15.4,80,950,5,11/9/2013 18:00,148160
110.3,16.5,75,955,5,11/10/2013 0:00,138900
109,17.9,70,960,5,11/10/2013 6:00,129640
108,19.4,65,965,5,11/10/2013 12:00,120380
107.5,20.4,60,975,4,11/10/2013 18:00,111120
107.1,21.5,40,990,3,11/11/2013 0:00,74080

A: You can use either size-scale field or the data-defined properties. In any case, you will want to change the symbol units from mm to map units. If the map (project CRS) units are not nautical miles, you will of course have to convert the values first.
Based on your sample data:

*

*Load the OpenLayers layer --> The project CRS will be set to Pseudo Mercator.

*Load your point data

*In data-defined properties, specify "RADIUS(m)" * 2 as the size (diameter)

*Make sure units are set to map units (not mm)

Since you are quite close to the equator and high precision does not seem to be an issue, you should be able to get away with using Pseudo Mercator. Otherwise things get more complicated because you cannot use OpenLayers layers directly since they only support Pseudo Mercator.


text:
Q: iframe .load event not firing I am trying to reload an iframe like the following:
var frameObject = $('#myFrame');
var frameAsInDom = frameObject[0].contentWindow;
var currentLocation = frameAsInDom.location;
frameObject.attr('src', 'about:blank');
frameObject.contents().remove(); // This was a desperate statement!!
frameObject.attr('src', currentLocation).load(function(){
   alert('iframe reloaded');
});

The problem is the iframe's .load event is not getting triggered at all. I am not getting the alert inside the load call back.

A: You are mixing the binding and triggering of the event,
See this code: http://jsfiddle.net/BvQuk/1/
HTML

<input id="uxButton" type="button" value="Reload the frame" />

JS
$(document).ready(function() {
    var iFrame = $('#myFrame');

    iFrame.bind('load', function() { //binds the event
        alert('iFrame Reloaded');
    });

    $('#uxButton').click(function() {
        alert('onButtonClick OR onBeforeReload');
        var newSrc = iFrame.attr('src') + '?c=' + Math.random(); //force new URL
        iFrame.attr('src', newSrc); //changing the src triggers the load event
    });

});

Hope that helps.

A: You have a JavaScript error: currentLocation is undefined. It's due to a typo on var currenctLocation.
working demo


text:
Q: Set target of directional light in THREE.js I have model far away from the origin, and I want a directional light to hit the model like sunlight would do.
I set a position and a target for my DirectionalLight:
export const dirLight = getDirectional();
function getDirectional()  {
    const dirLight = new DirectionalLight( 0xffffff, 1 );
    dirLight.position.set( 585000 + 10000, 6135000 + 10000, -500 + 5000);

    return dirLight;
};

const helper = new THREE.DirectionalLightHelper( dirLight, 1000 );
let t = new THREE.Object3D();
t.translateX(585000);
t.translateY(6135000);
t.translateZ(1000);
dirLight.target = t;
scene.add(dirLight);
scene.add(dirLight.target);
scene.add(t);
helper.update();
scene.add( helper );

I would expect the light direction now to be parallel to vector between light position and light target, but apparently the light direction is still towards the origin of the scene. What am I doing wrong ?
A running example can be seen here

A: The documentation states that the target needs to be added to the scene so that the world coordinates are calculated. However, that does not seem to work.
So, instead I tried manually updating the world coordinates, and that worked. Probably that will only work with a static target.
In your case that would be adding
dirLight.target.updateMatrixWorld();


text:
Q: Finding log2() using sqrt() This is an interview question I saw on some site.
It was mentioned that the answer involves forming a recurrence of log2() as follows:
double log2(double x )
{
if ( x<=2 ) return 1;
 if ( IsSqureNum(x) )
   return log2(sqrt(x) ) * 2;
 return log2( sqrt(x) ) * 2 + 1; // Why the plus one here.
}

as for the recurrence, clearly the +1 is wrong. Also, the base case is also erroneous.
Does anyone know a better answer?
How is log() and log10() actually implemented in C.

A: Perhaps I have found the exact answers the interviewers were looking for. From my part, I would say it's little bit difficult to derive this under interview pressure. The idea is, say you want to find log2(13), you can know that it lies between 3 to 4. Also 3 = log2(8) and 4 = log2(16),
from properties of logarithm, we know that log( sqrt( (8*16) )  = (log(8) + log(16))/2 = (3+4)/2 = 3.5
Now, sqrt(8*16) = 11.3137 and log2(11.3137) = 3.5. Since 11.3137<13, we know that our desired log2(13) would lie between 3.5 and 4 and we proceed to locate that. It is easy to notice that this has a Binary Search solution and we iterate up to a point when our value converges to the value whose log2() we wish to find. Code is given below:
double Log2(double val)
{
    int lox,hix;
    double rval, lval;
    hix = 0;
    while((1<<hix)<val)
        hix++;
    lox =hix-1;
    lval = (1<<lox) ;
    rval = (1<<hix);
    double lo=lox,hi=hix;
   // cout<<lox<<" "<<hix<<endl;
    //cout<<lval<<" "<<rval;
    while( fabs(lval-val)>1e-7)
    {
        double mid = (lo+hi)/2;
        double midValue = sqrt(lval*rval);

        if ( midValue > val)
        {
             hi = mid;
             rval = midValue;
        }
        else{
            lo=mid;
            lval = midValue;
        }
    }
    return lo;

}

A: It's been a long time since I've written pure C, so here it is in C++ (I think the only difference is the output function, so you should be able to follow it):
#include <iostream>
using namespace std;

const static double CUTOFF = 1e-10;

double log2_aux(double x, double power, double twoToTheMinusN, unsigned int accumulator) {
     if (twoToTheMinusN < CUTOFF)
       return accumulator * twoToTheMinusN * 2;
     else {
       int thisBit;
       if (x > power) {
            thisBit = 1;
            x /= power;
       }
       else
            thisBit = 0;
       accumulator = (accumulator << 1) + thisBit;
       return log2_aux(x, sqrt(power), twoToTheMinusN / 2.0, accumulator);
     }
}

double mylog2(double x) {
     if (x < 1)
       return -mylog2(1.0/x);
     else if (x == 1)
       return 0;
     else if (x > 2.0)
       return mylog2(x / 2.0) + 1;
     else
       return log2_aux(x, 2.0, 1.0, 0);
}

int main() {
     cout << "5 " << mylog2(5) << "\n";
     cout << "1.25 " << mylog2(1.25) << "\n";
     return 0;
}

The function 'mylog2' does some simple log trickery to get a related number which is between 1 and 2, then call log2_aux with that number.
The log2_aux more or less follows the algorithm that Scorpi0 linked to above.  At each step, you get 1 bit of the result.  When you have enough bits, stop.
If you can get a hold of a copy, the Feynman Lectures on Physics, number 23, starts off with a great explanation of logs and more or less how to do this conversion.  Vastly superior to the Wikipedia article.


text:
Q: Featured tab not displaying the number of questions next to it when looking at questions for more than one tag I pay attention to a group of tags by looking at the following URL:
https://stackoverflow.com/questions/tagged/emacs+or+elisp+or+emacs-lisp+or+dot-emacs
That works fine, and when you click on the 'Featured' tab, you get a list of the items featured.  However, the (non-zero) number of featured questions does not show up in the original page (the URL above), whereas if you look at only a single tag, you do get the non-zero number of featured questions next to the featured tab.
This is the case whether you or or and the tags together.

A: As it happens, the "featured" tab has worked for composite tags for a considerable time, which you can see by visiting tabs in a particular order, for example:

*

*https://meta.stackexchange.com/questions/tagged/feature-request?sort=featured

*https://meta.stackexchange.com/questions/tagged/feature-request+or+support
this is actually now showing you the featured questions for either tag, but the tab-header is conspicuously absent. However, starting from the next deploy, the "featured" tab works fully (including the tab-header / count) in all scenarios. Enjoy.


text:
Q: How can I do unit testing for retrofit callbacks? I'm trying to create unitest case for  retrofit 2 callbacks  in android. I use for test mockito, MockWebServer  and  MockResponse.
public class LoginFragment extends Fragment {
/**
     * Actualiza el numero telefonico para el usuario
     *
     * @param phoneNumber
     */
    public  void phoneNumber(String phoneNumber) {
        HttpService service = Service.createService(HttpService.class, TOKEN);
        Call<Void> call = service.phonumber(phoneNumber, new User("", ""));
        call.enqueue(callback());
    }

    /**
     * @return Callback<Void>
     */
    public Callback<Void> callback() {
        return new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    dummy();
                } else {
                    Log.e(TAG, "problema");
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, " " + t);
            }
        };
    }

    public void dummy(){
        System.out.println(" called");
    }
}

My unitest class:
@RunWith(MockitoJUnitRunner.class)
public class TestLoginFragment {
   MockWebServer mockWebServer;

    @Before
    public void setup() throws Exception {
        spyLoginFragment = mock(LoginFragment.class);
        mockWebServer = new MockWebServer();
    }

    @Test
    public void testDummyIsCalled() {
        spyLoginFragment.phoneNumber("3333335");
        mockWebServer.enqueue(new MockResponse().setResponseCode(201));
        verify(spyLoginFragment, times(1)).dummy();
    }
}

But when you run the test I get:
TestLoginFragment > testDummyIsCalled FAILED
    Wanted but not invoked:
    loginFragment.dummy();

I'm new making callback test, how can I verify that dummy() was called?

A: By definition, unit test only tests the functionality of the units themselves. Therefore, it may not catch integration errors.
You shouldn´t test the retrofit framework or its callbacks, you must be presumed that retrofit always works. Only Test your code, so create a test for phoneNumber(String phoneNumber) that checks if the service was configured correctly (not need to launch retrofit service), and create others test to check the posible responses from the server in OnSuccess or OnFailure cases.
PD: If you want to test the coupling between the Retrofit call and the callback's methods, then you're talking about "integration test".


text:
Q: Tkinter: window doesn't open That's my code and the subfunction is executed, but it doesn't get to mainloop().
If i comment out "update_Lux(labelLuxValue)" the window shows up.
I can't figure out why :(
from Tkinter import *

def update_Lux(label):
    label.config(text = str(dev.calcLux()))
    label.after(100, update_Lux(label))

def update_CT():
    labelCTValue.config(text = str(dev.calcCT()))
    labelCTValue.after(100, update_CT())

box = Tk()
box.title('TCS3490')
box.geometry('200x180')

labelLux = Label(master=box, text='Lux=')
labelLux.place(x=5, y=5, width=60, height=30)

labelCT = Label(master=box, text='CT=')
labelCT.place(x=5, y=30, width=60, height=30)

labelLuxValue = Label(master=box)
labelLuxValue.place(x=50, y=5, width=100, height=30)

labelCTValue = Label(master=box)
labelCTValue.place(x=50, y=30, width=100, height=30)

update_Lux(labelLuxValue)

box.mainloop()

A: You have infinite loops in your two methods update_Lux and update_CT.
This line
label.after(100, update_Lux(label))

should be
label.after(100, lambda: update_Lux(label))

or
label.after(100, update_Lux, label)

Otherwise you are passing not the update_Lux function to after, but the result of update_Lux(label)... and when that method is called, it again tries to pass the result to after, and so on and so on.

A: Ok, that worked well.
I have another problem now.
There is another function called "update_CT". The structure is the same.
Both in sequence won't work.
Including both in one "update" function like:
def update_LuxCT():
    labelLuxValue.config(text = str(dev.calcLux()))
    labelCTValue.config(text = str(dev.calcCT()))
    labelLuxValue.after(100, lambda:update_LuxCT())

works though :)
But why won't they work separately together?


text:
Q: obj1 *= obj2 VS. obj1 = obj1 * obj2 in C++ Assuming that i've implemented *=, = and * operators overloading, which will you prefer to use complexity wise?
Thanks.

A: Given that I'd usually implement operator * in terms of operator *= and a copy, there is no reason ever to prefer operator *.
The normal implementation of operator * (and +, -, / etc.) should usually look as follows:
T operator *(T const& left, T const& right) {
    T result = left;
    return result *= right;
}

A: Both usages are NOT complex for simple operations like the one you have specified. But, for longer expressions, *= can make things more readable.

A: If you've implemented them normally, then prefer *=.  The other way will require making a copy, then applying *= to it, then assigning it back.

A: The = and * separate implementations are more useful. It allows a * b * c * d type expressions. However consider the overhead of additional copies being created, as noted by Benjamin Lindley.


text:
Q: Como usar o Z3 da Microsoft em java? Estou fazendo um trabalho em que preciso integrar o Z3 da Microsoft ao java
Alguém sabe como fazer isso, tipo um passo a passo?

A: Tanto Scala quanto Java podem ser integrados com Z3.
Lembrando que Scala é uma das linguagens que rodam na Java Virtual Machine
http://lara.epfl.ch/w/ScalaZ3
Para Java, o próprio Leonardo Moura tem esse pequeno passo-a-passo:
https://leodemoura.github.io/blog/2012/12/10/z3-for-java.html
Não pude encontrar mais além desses.


text:
Q: Why am I receiving invalid pointer error when running this code I am receiving the following error when running this code.
Error in `main': free(): invalid pointer:
My idea is to use a pointer allocated through malloc. This is a sample code.
Please let me know why I am receiving this error.
#include <stdio.h>
#include <stdlib.h>
int main()
{
 int c=10;
 int* ptr = NULL;
 ptr = (int*)malloc(sizeof(int));

 if(ptr == NULL)
 {
   printf("Memory not allocated");
   exit(0);
 }

 ptr = &c;
 free(ptr);
 ptr=NULL;
}

A: int c=10;

Variable c allocated on the stack.
ptr = (int*)malloc(sizeof(int));

Assign address of allocated memory on the heap to ptr
ptr = &c;

Assign address of c to ptr.

You have two problems in your code.

*

*Memory Leak. You have lost address of allocated memory since you used reassign of ptr. In this case you don't have any other way to free memory allocated on the heap until program ends.

*You can't free memory allocated on the stack with free() function. It's auto variables

So, If you were trying to assign the value of c to the allocated space:
*ptr = c;

A:
Why am I receiving an invalid pointer error?

Because you free a pointer that was not allocated with malloc (or realloc).
You have a memory leak, i.e. you lose a malloced pointer with ptr = &c, which assigns the address of c to ptr, losing the value returned by malloc.

A: Well to do that you need to allocate for a pointer of pointer like this
#include <stdio.h>
#include <stdlib.h>

int main() {
 int c=10;
 int** ptr = NULL;
 ptr = (int**)malloc(sizeof(int*));

 if(ptr == NULL)
 {
   printf("Memory not allocated");
   exit(0);
 }

 *ptr = &c;
 free(ptr);
 ptr=NULL;
}

the problem in your case that you are freeing a non dynamic allocated memory and that gives you an error, and even in other cases you should always keep the address of the allocated memory to free it when you no more need it for example
#include <stdio.h>
#include <stdlib.h>

int main() {
 int *ptr1 = (int*)malloc(sizeof(int));
 int *ptr2 = (int*)malloc(sizeof(int));
 *ptr1 = 5;
 *ptr2 = 10;
 // this is wrong because now there is no way to free
 // the address of the allocated memory to ptr1
 ptr1 = ptr2;
 free(ptr1);
 // this gives an error because ptr2 is already free
 free(ptr2);
}

Conclusion:
If you want to allocate to store a pointer, then you need to allocate for a pointer to pointer, so the pointer of the allocated memory stay so you can free that memory when you no longer need it


text:
Q: Transactional replication in SQL SERVER When we altering any database objects at publisher, we have received below error messages.

#table_name table - Unable to modify table.
  Cannot drop the table #table_name because it is being used for replication.

How can we alter DB objects at publisher those are involved in replication (without deleting published articles)?
Anybody suggest us further.


text:
Q: Query array of subdocuments I have a chatRooms collections like following:
{ "name" : "Room1", "users" : [  {  "userId" : 1 },  {  "userId" : 2 } ] }
{ "name" : "Room2", "users" : [  {  "userId" : 1 },  {  "userId" : 4 } ] }
{ "name" : "Room3", "users" : [  {  "userId" : 2 },  {  "userId" : 3 } ] }
{ "name" : "Room4", "users" : [  {  "userId" : 2 },  {  "userId" : 1 } ] }

Now I want the Room(s) where userId 1 and 2 is in.
I should get Room 1 and 4.
I tried different things like
db.chatRooms.find({users: {$elemMatch: {userId: 1, userId: 2}}})

But nothing is working. Any Idea ?

A: You should use $all operator
db.chatRooms.find({users:
    {$all : [
       {$elemMatch: {userId: 1}}
      ,{$elemMatch: {userId: 2}}
    ]}
})

Simplified version
db.coll.find({users:
    {$all : [
       {userId: 1}
      ,{userId: 2}
    ]}
})


text:
Q: Обновление значений в базе данных Я записываю 2 значения в базу данных таким орбазом:
В одной из функции: zapis(message.chat.id, 0)
Этой функцией является:
def zapis(user_id, Type):
    with sqlite3.connect(path_to_db) as db:
        db.execute("INSERT INTO storage "
                   "(user_id, Type) "
                   "VALUES (?, ?)",
                   [user_id, Type])
        db.commit()

После чего, мне требуется ОБНОВИТЬ эту базу данных вот таким значением:
zapis_type(message.chat.id, Type='Text')
def zapis_type(user_id, Type):
    with sqlite3.connect(path_to_db) as db:
        db.execute(f"UPDATE storage SET Type={str('TEXT')} WHERE user_id={user_id}")
        db.commit()

И после чего выдаёт вот такую вот ошибку, как пишет Visual Studio:

Exception has occurred: OperationalError (note: full exception trace is shown but execution is paused at: process_message)
no such column: TEXT

A: Ваша проблема в форматировании в этой строке:
db.execute(f"UPDATE storage SET Type={str('TEXT')} WHERE user_id={user_id}")
Функция str никакого отношения к интерпретации переданного параматра базой данных не имеет. В итоге база получает строку
UPDATE storage SET Type=TEXT WHERE user_id=1
и вполне логично ищет поле TEXT.
Правильный вариант:
db.execute(f"UPDATE storage SET Type='{'TEXT'}' WHERE user_id={user_id}")
ковычки вынесены в запрос.
PS: проблемы правда на этом не заканчиваются, поработайте над неймингом своих функций и почитайте про sql-инъекции.


text:
Q: List not updating when using Openpyxl First question here so bare with me.
I'm currently working on developing an automated web scraping system for my company's database, however i've ran in to a bit of an issue i can't seem to figure out.
I won't post the entire code here as it's a lot to sift through, but explaining the issue will hopefully be enough with a little snippet.
Partway down my Python code, i extract the data from my Excel spreadsheet in to a list, however for some reason, the list doesn't actually update until after the program has terminated?
For example the length of the list will print 0 after writing to it, but the next time i run the program, the list is full and printing the correct number of elements.
This is troublesome as i need to work with that list directly after by comparing it to another list, to check for missing data...any ideas what this could be? The code is below:
    excel_updates_check_inner_list = []
    excel_updates_check_list = []

    for i in range(0, excel_list_size-1):
        updates_stock_name = db.cell(row= 2+i, column= 2).value
        updates_stock_location = db.cell(row= 2+i, column= 3).value
        updates_stock_dimensions = db.cell(row= 2+i, column= 4).value
        updates_stock_price = db.cell(row= 2+i, column= 5).value
        updates_stock_hire = db.cell(row= 2+i, column= 6).value
        excel_updates_check_inner_list = [updates_stock_name, updates_stock_location, updates_stock_dimensions, updates_stock_price, updates_stock_hire]
        excel_updates_check_list.append(excel_updates_check_inner_list)

    excel_updates_check_list.sort()
    print(len(excel_updates_check_list))

I've tried saving the excel sheet directly before executing this chunk of code, but still with no luck.

A: I solved it by just using Pandas instead. For some reason there is some kind of read-in lag with Openpyxl. With Pandas i just created the dataframe and extracted the information from there in to subsequent lists.


text:
Q: Using pure Ember to create SVG chart with transition effect I'm trying approach in this link D3 and React - the future of charting components? to create some charting components without using d3 to generate svg elements.
Now I could do the most simplest case: if I have an array [1, 1, 1], I will get a series of bars with height equal to 1. When I change the array to [2, 2, 2], I get a series of new bars with height equal to 2 instantly.
What I want to have is, when I change data array, the bar could change height with an animation effect. For the above input, the second time height of each bar would grow from 1 to 2.
Inside my component I use each to iterate through values
{{#my-svg}}
  {{#each values as |v|}}
    {{my-rect height=v ........}}   // my own component
  {{/each}}
{{/my-svg}

It looks like Ember will destroy and recreate all rect components instead of doing virtual dom like diff to change their height property (I'm using Ember with glimmer engine). Therefore my css transition property no longer works. (It works if I only have one <rect>)
Another way in my mind is adding oldHeight newHeight for each bar, use other jquery library to change height with transition based on those two values. But if that so I need to run this function for every bar, which sounds very slow. I'm wondering is there any better to achieve it.


text:
Q: Short Story involving an investigation into crimes at a designer baby facility, ending implicates eugenics I'm pretty sure I read this in the late 1980s to the early 1990s in Ashland, KY, in an anthology of science fiction. Someone was sent in to investigate crimes at a facility for designer babies. I don't remember if there had been an actual murder, destruction of property, or simply too many accidents. I have a vague memory of them suspecting religious terrorists, possibly with the investigator being pressured to pick them as suspects because they made for the right narrative. I'm pretty certain that the babies were described as being gestated in glass jars in racks, complete with an evocative scene of sabotage with broken glass and fluid on the floor. The investigator manages to figure out who the suspect is.

 It's one of the doctors, who I want to say was not Caucasian, who claimed that he was trying to draw attention to the fact that parents were practicing passive eugenics by eliminating traits they found less desirable, resulting in too much homogeneity among the children.

After the suspect is taken away by the police, while everyone is congratulating themselves on finding the culprit and safely locking them away, the investigator looks at the rack and muses that every one of the growing babies he can see has blond hair, pale skin, and blue eyes.

A: For the record, Covertwalrus had it correct. It is indeed "Brave Newer World" by Harry Harrison. I likely read it in Stainless Steel Visions. It has the sabotaged bottles and an ending revealing that the motivation was preventing the creation of a world of blue-eyed blond children.
I have found that I misremembered part of the premise. The bottles were apparently just failing at first, not being obviously destroyed. Defective valves delivering the wrong doses of chemicals, killing off one or two dozen bottles at a time. The villain is introduced early on, arguing about how the eugenics going on to pick "good genes" paid little attention to diversity, while another doctor agonizes over how she wants to think of the bottled fetuses as people who'd had their lives snuffed out when obviously she should believe them to just be cell lines. Other aspects of the futuristic world include "kidney pills" and diagnostic machines which have rendered doctor visits into placebo demonstrations, complete with an artificially chilled stethoscope that's plugged up with wax so that the doctor's not distracted by an actual heartbeat, since analysis machines do all of the work. Geriatrics is highly advanced, with the treatments being more available to people with fewer children, sharply dropping the "natural" childbirth rate. The protagonist is one of the remaining doctors, contacted by an FBI agent who is there to inspect the bottle failures (10 times that of other new cities), because the government has invested a lot of money in the process. There's a scene at a hip "ethnic" restaurant with the female doctor and her husband that throws a number of non-white ethnicities together from the black manager to the Native American drummer to the Hawaiian dancer, and indicates that natural childbirth is possible, still at an advanced age, but the health system pushes towards people donating their sperm and ova to be used on the bottle babies, again by controlling the health care.
Shortly thereafter, the previously mentioned female doctor finds smashed up bottles, with a hammer lying amongst them. She's caught on the scene by the FBI agent, who seems convinced she is the perpetrator. It soon becomes revealed that her husband is having an affair with a black secretary in the office. Analysis of the names involved in the destroyed bottles are revealed to not belong to donors with Afrikaaner or Negro (the terms used in the story) names but instead to Italian, Irish, Anglo-Saxon, and German names.
Dr. Livermore, the doctor introduced at the beginning, is confronted, and he admits that he was the one who was destroying the bottles after the agent suggests him as a likely subject due to the fact that no bottles with ethnic names have been destroyed, and that he is on the record as stating that ethnic minorities are being discriminated against. He admits to the crime, and goes on a short diatribe about how he tried to influence gene selection legally, but found that no matter how hard he tried, the government kept predominantly selecting white donors as the ones with "correct" genes to be included in the banks. When told that he'll quietly be released from his job to prevent this from becoming publicly known, he insists that he will make a stink about it publicly, forcing this into a court case, and that they have no way of preventing him from doing it, since they have no actual evidence against him (he'd avoided leaving records, and had sabotaged the recording device the agent thought was running). The story ends with the female doctor and her husband reconciling, and the owner of the ethnic restaurant deciding to move into bagels because it was what the growing white population desired.
So, ultimately, I was wrong on several points. There were no terrorists, no invocation of religion, and nobody learns a lesson from it.


text:
Q: Checkpoint R75 Security Gateway without default route I've set up a virtual lab network in vmware with two networks. vmnet2 (192.168.100.0/24) and vmnet3 (192.168.200.0/24).
My R75 is having the ip addresses 192.168.100.1 and 192.168.200.1, and is the default gateway for both of these networks.
This firewall will inspect and route packets from the 192.168.100.0/24 network to 192.168.200.0/24, and vica versa.
However, during the configuration phase of the R75, I am forced to set a default gateway. In my setup, this does not make any sense, as my lab only have two networks, and no other routers.
Is my setup too unrealistic for checkpoint, or do I just miss some knowledge about the need for a default gateway?

A: Shouldn't matter what the default gateway is.  My guess is that Check Point asks for it to determine what interface should be considered "External" for the topology configuration.  Whatever lab network is less trusted is where you should point your default gateway.
If it's asking while you're installing SecurePlatform, you can probably just remove the default gateway after the install is complete within the web admin tool.

A: There is no harm in having a default gateway, you can set it to anything (reachable). It won't be use for traffic within the two connected networks anyway.


text:
Q: What is the most efficient way to find union of two collections? public IEnumerable<SummaryItem> GetSummaryData(SummarySettings settings)
{
   return GetSummaryReportData(startTime, endTime, settings.AgentIds);
}

After I wrote my code I realized that I need to add  some ids to the settings.AgentIds.
So I do the following
public IEnumerable<SummaryItem> GetSummaryData(SummarySettings settings)
{
    if (settings.LabelIds != null && settings.LabelIds.Any())
    {
       var labelGroups = _agentsGroupsStorage.Values.Where(x => settings.LabelIds.Contains(x.Id));
       var labelAgentIds = labelGroups.SelectMany(x => x.AgentIds); // IEnumerable<Guid>

       settings.AgentIds = new GuidCollection(labelAgentIds.Union(settings.AgentIds).ToList());
    }

   return GetSummaryReportData(startTime, endTime, settings.AgentIds);
}

How can I improve my algorithm to combine two collection?
Maybe without creating new GuidCollection ? Or I need to use Aggregate but not Union?

A: Here is the approximate implementation of a Union:
public IEnumerable<T> Union(this IEnumerable<T> left, IEnumerable<T> right)
{
    var hs=new Hashset<T>(left);
    for(var item in right)
    {
        hs.Add(item);
    }
    return hs;
}

As you can see, it makes use of a set-based collection to make the union. This leverages the speed of hash tables to make the operation very efficient indeed. It might be possible to make a more optimal solution with fore-knowlege of the data that you are trying to collect, but in the general case, this is as quick as it gets.


text:
Q: How do I target a single input focus? How would I target a single input focus.
    $(".right input").focus(function(){
    $(".left span").addClass('focus');
}).blur(function(){
    $(".left span").removeClass('focus');
});

This code adds the class to all of the span elements when I focus on an input
How would I set it so it can only add the class to the input that is being focused?
Here is my html

Your Name:
<input id="name" type="text" value="Name" autocomplete="off">

Email Address:
<input id="email" type="text" value="Email" autocomplete="off">

Phone Number:
<input id="phone" type="text" value="Phone" autocomplete="off">

Your Address:
<input id="address" type="text" value="Address Line 1" autocomplete="off">

Line Address 2:(optional)
<input id="address2" type="text" value="Address Line 2" autocomplete="off">

Edit
Could I implement the code given in the answer selected to this code?
        // Trying to target font customization on single input focus
    // and not all together
    $("#fs").change(function() { // change font family style.
        $('.email').css("font-family", $(this).val());
    });
    $("#size").change(function() { // change font size.
        $('.email').css("font-size", $(this).val() + "pt");
    });

To edit the span belonging to the input that is focused on?

A: use this reference
 $(".right input").focus(function(){
    $(".left").find('.'+this.id).addClass('focus');  //<--find element with those classes inside .left element
 }).blur(function(){
   $(".left").find('.'+this.id).removeClass('focus');
 });

A: $('.right input').each(function(){
  var id = $(this).attr('id');

  $(this).bind('focus', function(){
     $('.left').find('.'+ id).addClass('focus');
  });

  $(this).bind('blur', function(){
    $('.left').find('.'+ id).removeClass('focus');
  });
});

A: try this
demo fiddle
 $(".right input").focus(function(){
     var cls = $(this).prop('id');
     $(".left span."+cls).addClass('focus');
 }).blur(function(){
     $(".left span").removeClass('focus');
 });

A: Try this,
$(".right input").focus(function(){
    $(".left span."+this.id).addClass('focus');
}).blur(function(){
    $(".left span."+this.id).removeClass('focus');
});

Demo


text:
Q: criar um novo dataframe tendo referência outro Possuo um dataframe com (1242 rows × 325 columns) dele faço uma correlação ".corr()" que resulta em (325 rows × 325 columns)
esse código me exibe as 15 menores correlações do menor valor para o maior valor com base no "ABEV3" (15 rows × 1 columns)
ppl = 'ABEV3'
papel = corr[ppl]
corr.query('@papel < 0.1')[ppl].sort_values(ascending=True).head(n=15).index.to_frame().rename(columns={0: ppl})

        ABEV3
PATI3   PATI3
ENMT3   ENMT3
RNEW11  RNEW11
CEDO3   CEDO3
RNEW3   RNEW3
BDLL4   BDLL4
CAMB3   CAMB3
ESTR4   ESTR4
CAMB4   CAMB4
SPRI3   SPRI3
DTCY3   DTCY3
MAPT4   MAPT4
BMEB3   BMEB3
ELEK4   ELEK4
LIPR3   LIPR3

A minha dificuldade é em listar (15 rows × 326 columns) sendo que cada coluna fosse o correlacionado e na primeira coluna sendo numerado pela quantidade de linhas, um exemplo feito manualmente:
ppl = corr.columns # lista/exibe os indexes das colunas

# executando ppl
ppl
Index(['^BVSP', 'AALR3', 'ABCB4', 'ABEV3', 'ADHM3', 'AGRO3', 'ALPA3', 'ALPA4',
       'ALSO3', 'ALUP11',
       ...
       'VLID3', 'VULC3', 'VVAR3', 'WEGE3', 'WHRL3', 'WHRL4', 'WIZS3', 'WLMM4',
       'WSON33', 'YDUQ3'],
      dtype='object', length=325)

papel = corr[ppl]
corr.query('@papel < 0.1')[ppl].sort_values(ascending=True).head(n=15).index.to_frame().rename(columns={0: ppl})

# quero que o resultado saia com essa estrutura
    ABEV3   PATI3   ITUB4
1   PATI3   MRSA3B  REDE3
2   ENMT3   FLRY3   ESTR4
3   RNEW11  MGLU3   CAMB3
4   CEDO3   SPRI3   DTCY3
5   RNEW3   TUPY3   ENMT3
6   BDLL4   CRPG6   CEDO3
7   CAMB3   USIM3   NORD3
8   ESTR4   TASA4   ELEK4
9   CAMB4   CAMB4   CAMB4
10  SPRI3   LLIS3   CTNM3
11  DTCY3   GEPA4   BMEB3
12  MAPT4   SLED3   MAPT4
13  BMEB3   CPLE6   PATI3
14  ELEK4   PTNT4   SPRI3
15  LIPR3   INEP4   PATI4

Não consigo encaixar essa linha dentro de um FOR, ou algum meio que me possa retornar como o exemplo que citei, tenho poucos meses que venho aprendendo, minha estrutura de repetição é muito vaga.


text:
Q: After publishing application on IIS server mimetype of xlsx file returning application/octet-stream I am trying to fetch mime type from file content. It is working fine on IIS Express and IIS configured on windows 10 locally, but when I published application to windows 2012 server. Mime of xlsx file returning application/octet-stream.
Public Shared Function GetMimeType(ByVal file As String) As String
        Dim mime As String = Nothing
        Dim MaxContent As Integer = CInt(New FileInfo(file).Length)
        If MaxContent > 4096 Then
            MaxContent = 4096
        End If

        Dim fs As New FileStream(file, FileMode.Open)

        Dim buf(MaxContent) As Byte
        fs.Read(buf, 0, MaxContent)
        fs.Close()
        Dim result As Integer = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, Nothing, 0, mime, 0)

        Return mime
    End Function

    <DllImport("urlmon.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True,

        SetLastError:=False)>
            Private Shared Function FindMimeFromData(
                ByVal pBC As IntPtr,
                <MarshalAs(UnmanagedType.LPWStr)>
                ByVal pwzUrl As String,
                <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.I1, SizeParamIndex:=3)> ByVal _
                pBuffer As Byte(),
                ByVal cbSize As Integer,
                <MarshalAs(UnmanagedType.LPWStr)>
                ByVal pwzMimeProposed As String,
                ByVal dwMimeFlags As Integer,
                <MarshalAs(UnmanagedType.LPWStr)>
                ByRef ppwzMimeOut As String,
                ByVal dwReserved As Integer) As Integer
            End Function

I expect to get output of file xlsx as application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
IIS MimeType Scanpshot


text:
Q: Resize a RAID 1 volume on OS X Snow Leopard - how? (Note: software raid) I've scoured the Internet in search of an answer to this question, and as usual with OSX-related topics, I often don't find any deep-dive technical explanations sufficient enough to feel confident doing dangerous things.
Here is my question:  I have a Mac Pro, running OS X 10.6.2.  I have, as my main root/boot disk, a RAID 1 volume called "Mirror1".  Mirror1 is comprised of two 1 TB disks.  Mirror1, however, is fixed at 640 GB.  That's because, I originally took a 640GB disk, bought a terabyte disk, mirrored it (using diskutil appleraid enable), when it synced I removed the 640GB and replaced it with a second 1 TB disk, and synced again.  Voila!  A single 640 GB replaced by two 1 TB disks in a mirror..  Actually, no.  There's still something missing from the equation:  Mirror1 needs to be expanded from  640GB to 1 TB to match the partition sizes on each of those disks.
How do I do this?
Perhaps the diskutil output will help:
-> diskutil list
/dev/disk0
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:      GUID_partition_scheme                        *1.0 TB     disk0
1:                        EFI                         209.7 MB   disk0s1
2:                 Apple_RAID                         999.9 GB   disk0s2
3:                 Apple_Boot Boot OSX                134.2 MB   disk0s3
/dev/disk1
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:      GUID_partition_scheme                        *1.0 TB     disk1
1:                        EFI                         209.7 MB   disk1s1
2:                 Apple_RAID                         999.9 GB   disk1s2
3:                 Apple_Boot Boot OSX                134.2 MB   disk1s3
/dev/disk2
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:      GUID_partition_scheme                        *640.1 GB   disk2
1:                        EFI                         209.7 MB   disk2s1
2:                  Apple_HFS Mac Disk 2              536.7 GB   disk2s2
3:       Microsoft Basic Data BOOTCAMP                103.1 GB   disk2s3
/dev/disk3
#:                       TYPE NAME                    SIZE       IDENTIFIER
0:                  Apple_HFS Mirror1                *639.8 GB   disk3
-> diskutil appleraid list
AppleRAID sets (1 found)
===============================================================================
Name:                 Macintosh HD
Unique ID:            1953F864-B474-4EB6-8E69-41834EBD0247
Type:                 Mirror
Status:               Online
Size:                 639.8 GB (639791038464 Bytes)
Rebuild:              manual
Device Node:          disk3
-------------------------------------------------------------------------------
#   Device Node       UUID                                   Status
-------------------------------------------------------------------------------
0   disk1s2           25109BAE-5697-40EA-B612-0217851444F7   Online
1   disk0s2           11B83AB0-8148-4DB6-8761-DEF08C855F8D   Online
===============================================================================

Thanks in advance.

A: I don't know of a way to do it directly, but you can get the same effect if you're willing to take the long way around:
1) Remove one of the disks from the existing mirror.
2) If you want a backup during this process, re-add the 640GB disk and sync, then remove it.
3) Reformat the removed terabyte disk as a new unpaired mirror.
4) Boot from something else (install DVD works, Terminal is available under the Utilities menu), and do a high-fidelity clone from the old to new RAID (I'd use asr restore --source /Volumes/OldRAID --target /Volumes/NewRAID --erase).
5) Erase the old RAID disk, add to new RAID, sync.
The big problem here is that the server is offline while for a while (step 4).  If that's not an option, you may be able to get by with a lower-fidelity cloning method that'll at least partly work while the server is online:
4a) Use Carbon Copy Cloner to clone the (still-mounted) old RAID to the new one.  Alternately, compile the latest version of rsync (Mike Bombich has instructions) and use that to do the clone.  Note that, as usual for an online backup, this won't reliably get a consistent snapshot of files being actively modified.
4b) Boot from something else, and rerun CCC/rsync (Install DVD may not do the job this time, as it doesn't have CCC, rsync, or even the Finder).
4c) Rename the new RAID volume the same as the old one.
You'll still be offline for a bit, but not as long since it only has to copy modified files.  Unfortunately, this won't make as high-fidelity a copy as asr would, but it's pretty good (see the Backup Bouncer results on Bombich's site) -- the only things I know of offhand that it'll change is file IDs, and undoing the (transparent) compressed format some OS files are stored in.


text:
Q: Business Objects and dynamic sql I had this idea and my first reaction after having it was "That's a great idea, but why have I never seen/heard it talked about before??"  So I'm hoping you can tell me if there is some framework out there that already does this, or if there is some reason why I should avoid it.
The idea is to create a base business object class with methods to dynamically write CRUD sql queries based on the name of the derived class and its properties (or aliases specified in  attributes).
My thinking is that once I do this I could just create a new class like so:
class Customer: BusinessObjectBase
{
    int Id {get;set;}
    string Name {get;set;}
    string Phone {get;set;}
}

and my Customer class, having access to BusinessObjectBase's CRUD methods, would be done.
Somethings to keep in mind when answering this:  For the sake of this question I'm highly interested in the design goals of decreased development time and low maintenance, and security is about a 3 on a scale of 1 to 10.  In other words, I'm not interested in hearing answers telling me I should be using stored procedures to access data because they are more secure, or anything along those lines.
I know the users here are pretty liberal with the close votes when it comes to overly broad questions... so just to be safe let me reiterate the question, which is not too broad:
Are there any existing frameworks to do this or is there any compelling reason why I should not?

A: It has been done before; many times, many ways.   The basic concept your thinking of is called 'model first' development.   You can do model first in Entity Framework, NHibernate, Subsonic and many other ORM style-frameworks.    Another incarnation of this line of thinking is LINQ-to-SQL where LINQ knows what queries to generate, whether or not you have CRUD stored procs.
Before ORM's were mainstream we use code files (codified in T4 style templates these days) to write out what your describing.  The whole idea was based on 'convention' meaning if a field is named ID then it must be the clustered-PK and so on.
Disclaimer
With that said, there is a down side to this line of thinking.   In your typical web app (or insert your app style here) you have three layers to work with--- client, middle, and DB.  With model/code-first development you are effectively ignoring one of the three layers.   Modern hardware has gotten quick enough that you can do this for most sites.  When your site grows in volume & complexity, however, you will often find yourself working around this auto-crud setup for your most complex/frequently-used scenarios.
Anyway, hope that helps.


text:
Q: Logical Equivalence - Difference between ∃x∀y P(x , y) and ∀y∃x P(x , y) I must be missing something here because these two statements look identical to me in regards to their truth tables. To me, ∃x∀y P(x , y) and ∀y∃x P(x , y) are logically equivalent...
a) What is the difference between the quantification
∃x∀y P (x , y) and ∀y∃x P (x , y), where P (x , y) is a
predicate?
b) Give an example of a predicate P (x , y) such that
∃x∀y P (x , y) and ∀y∃x P (x , y) have different truth
values.

A: a)"There exists x such that for all y ..." is much stronger than the second one.In other
words, this implies the other since in the second statement you may choose different x values
for different y values.
b)There exists x such that for all y    :$x>y$    $\hspace{17mm}  $   (F)
For every y there is x such   that      :$x>y$    $\hspace{22mm}  $   (T)


text:
Q: I get a error "IndentationError: unindent does not match any outer indentation level" I get this error:
Traceback (most recent call last):
  File "bin/mybrowser", line 32, in <module>
    import mybrowser
  File "/home/shaunyo/mybrowser/mybrowser/__init__.py", line 14, in <module>
    from mybrowser import MybrowserWindow
  File "/home/shaunyo/mybrowser/mybrowser/MybrowserWindow.py", line 32
    def on_refreshbutton_clicked(self, widget):
                                          ^
IndentationError: unindent does not match any outer indentation level

This is my code:
    self.refreshbutton = self.builder.get_object("refreshbutton")

    def on_refreshbutton_clicked(self, widget):
    print "refresh"

Does anyone know what's wrong?

A: I think you should have your code like
<TAB> self.refreshbutton = self.builder.get_object("refreshbutton")
<TAB> def on_refreshbutton_clicked(self, widget):
<TAB> print "refresh"

in your editor give a TAB everytime while entering in a new line.
Ok @Shaun
I think your code should look like
frank@FRANK-NATHE:~$ cat h.py
self.refreshbutton = self.builder.get_object("refreshbutton")
def on_refreshbutton_clicked(self, widget):
    print "refresh"

so don't use a tab for the 1st and 2nd lines and then use a tab for the 3rd line
If you still get confused then

A: It looks like that the code is with the refresh function is not being run. Try indenting these highlighted lines an extra tab.

becomes

so that the code is run in the finish_initializing() function. Python is very particular with it's indentation
Note that the self.refreshbutton line is in line with the # Code for other... comment in the 2nd image


text:
Q: Need some Python datetime magic Hey all. I don't think this should be very complicated but I just can't get it. I have a list of datetime objects starting at a certain date and ending at one. Some days can be skipped. I can print them out like this:
for entry in dates:
    print entry

Which gives me the following output:
2010-11-29 10:00:00.0
2010-12-30 10:00:00.0
2010-12-01 10:00:00.0 # Note that December 3rd has been skipped
...
2010-12-07 10:00:00.0

What I'd like to do is get an output like this:
Day 1: ok
Day 2: ok
Day 3: skipped
Day 4: ok
...
Day 10: ok

Could anybody help me out with some common sense here?
Thanks!

A: Here is a way to do this by converting your datetimes to dates. Rather than try to iterate over the dates themselves, we take a timedelta of the last date and the first date (this requires your dates to be sorted, I added a sorted call in case they aren't). Then we see if the first date plus the number of days is in your original set for each day in the range:
from datetime import datetime, timedelta
dts = [datetime(2010, 11, 29, 10, 0, 0), datetime(2010, 11, 30, 10, 0, 0),
       datetime(2010, 12, 4, 10, 0, 0)]
dates = sorted(d.date() for d in dts)

for d in range((dates[-1] - dates[0]).days + 1):
    st = 'ok' if dates[0] + timedelta(days=d) in dates else 'skipped'
    print 'Day %d: %s' % (d + 1, st)

Output:
Day 1: ok
Day 2: ok
Day 3: skipped
Day 4: skipped
Day 5: skipped
Day 6: ok

Note: I created my own example here because I'm not sure the example you used actually makes sense.

A: use the "rrule" module from the dateutil package, found at http://labix.org/python-dateutil
import datetime
from dateutil import rrule

dates = (datetime.datetime(2010, 11, 29),
         datetime.datetime(2010, 11, 30),
         datetime.datetime(2010, 12, 2))

all_dates = list(rrule.rrule(rrule.DAILY, count=5,
                 dtstart=datetime.datetime(2010, 11,29)))

for (i, date) in enumerate(all_dates):
    if date in dates:
        status = "ok"
    else:
        status = "skipped"

    print "Day %s: %s" % (i+1, status)


text:
Q: In MATLAB is there a way to get the result of find(), on a 3-D matrix, as a jagged array of linear indices? I have a Matrix of size 404x15x15. For each of the 404 pages, I want to get linear indices of the remaining 15x15, but in a way that is suitable for vectorisation. This is easy in a for loop as I can do:
vals = rand([404, 15, 15]);
m1 = rand([15, 15]);
m2 = rand([15, 15]);

jag1 = cell(404);
jag2 = cell(404);
results = zeros(404);

for i=1:404
    ind_to_sum = find(vals(i,:,:) <= 0.5);
    jag1{i} = m1(ind_to_sum);
    jag2{i} = m2(ind_to_sum);

    results{i} = some_unimportant_function(vals(i,:,:), jag1{i}, jag2{i});
end

Here each element of jag1, jag2 is the list of values in m1, m2 corresponding to the indices where vals satisfies the condition. Instead of using a for loop, I am trying to find a way to vectorise this, which needs a version of find() that allows a specific dimension to be ignored, and then return a jagged array. I feel like this shouldn't be unreasonable, as each iteration of the for loop is completely independent from the others. Is there any such function, or perhaps a different strategy that I could use?


text:
Q: How to number a newtheorem the same as one written before In one section I wrote some numbered hypothesis, for which I created a theorem environment as follows:
\newtheorem{ipotesi}{Ipotesi}%[section]
\renewcommand{\theipotesi}{A\arabic{ipotesi}}

In another section, far away from the one where I put firstly my hypothesis, I would like to rewrite them using again the same environment, with the same number of course and possibly a cross reference that points exactly to the first ones.
Here I found something but I am not able to apply it to my case
From what I deduced, I should write something like this, but it does not work.
\makeatletter
\newcommand{\neutralize}[1]{\expandafter\let\csname c@#1\endcsname\count@}
\makeatother

\newtheorem{hp}{Ipotesi}

\newenvironment{hpbis}[1]
  {\renewcommand{\thehp}{\ref{#1}}%
   \neutralize{hp}\phantomsection
   \begin{hp}}
  {\end{hp}}

I managed to solve the problem using \addtocounter{ipotesi}{-x} where x is the number of hypothesys I wrote in between the sections. However, this does not fully satisfies me..
Can anyone please explain me what does the code written by @egreg and also how could I manage do make this working more properly?


text:
Q: I cannot load a texture from a file (SFML c++) When I use the function .loadFromFile(), i get the following error:
undefined reference to `sf::Texture::loadFromFile(std::__cxx11::basic_string, std::allocator > const&, sf::Rect const&)'|
I have already tried different versions of SFML, and according to their website I'm using the correct one.
Here is my setup:
codeblocks-17.12mingw-setup.exe => download for codeblocks
SFML-2.4.2-windows-gcc-4.9.2-tdm-32-bit => SFML I am using
Here are my settings:

in the compiler tab

in the linker tab

The linking should be ok, as all the other SFML functions work. I have read that it could be because of SFML being compiled by a different compiler than mine? How can I check that? Is it something else that causes this problem?
here is the code :
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>

using namespace sf;

int main () {

Texture texun;
    texun.loadFromFile("C:\\Users\\j_hyl\\OneDrive\\Bureaublad\\Webdev\Apps\\Drive\\sprite.bmp");

return 0;
}

A: you have to link to sfml-graphics.lib or if your configuration is debug you have to link with sfml-graphics-d.lib  and you have to copy the sfml-graphics-2.dll and sfml-graphics-d-2.dll(if debugging conf.) to the folder where your executable is


text:
Q: OpenVPN client source port keeps changing, TLS fails This problem only happens behind certain routers/gateways and i have no control over. this is my clients connecting over public internet. what seems to be the problem is that the source PORT changes almost instantaneously. and yes this is only specific to certain devices for example fortigate devices when they are the gateway. and yes i ruled out the devices, my gateway, my server, everything. since when they try over Cellular it works immediately. i don't know what's wrong with these gateways and why do they do that.
Also, could it be an issue when there is asymmetric wan routing taking place ?
i'm using TCP and NOT UDP. i tried UDP and still the same.

Tue Mar 12 00:11:47 2021 X.X.X.X:47804 TLS: Initial packet from [AF_INET]X.X.X.X:47804, sid=(bla bla bla )

Tue Mar 12 00:11:49 2021 X.X.X.X:47807 TLS: Initial packet from [AF_INET]X.X.X.X:47807, sid=(WHATEVER)

Tue Mar 12 00:11:51 2021 X.X.X.X:478XX TLS: Initial packet from [AF_INET]X.X.X.X:478XX, sid=(WHATEVER)

and it keeps on and on ( TLS failed and Client instance restarting ) and XX keeps incrementing
is there any way to "POKE" a NAT port open till the client finishes the negotiation ? i set Keep-alive to 1 second which is the bare minimum i think and still
thanks in advance, i'm losing my mind over this
EDIT :
someone also seems to have that exact problem HERE IS A SCREENSHOT

A: You have no problem with the VPN, your problem is with the TCP connection that is probably restricted by the Fortigate firewall (fortigate device) you mentioned.
The way to solve this is to talk to the administrator of the firewall and ask for permission to contact the VPN server.


text:
Q: Guideline 5.1.1 - Legal - Privacy - Data Collection and Storage Got some error rejection from app store.
We found in our review that your app does not meet all of our requirements for apps that offer highly regulated services or handle sensitive user data. Specifically:

- The app must be published under a seller and company name that is associated with the organization or company providing the services. In this case, your app must be published under a seller name and company name that reflects the <APP_NAME> name.

The guideline 5.1.1(ix) requirements give App Store users confidence that apps operating in highly regulated fields or that require sensitive user information are qualified to provide these services and will responsibly manage their data.

Next Steps

To resolve this issue, it would be appropriate to take the following steps:

- Your app must be published under a seller name and company name that reflects the <APP_NAME> name. If you have developed this app on behalf of a client, you may resubmit the app through their account, if they have one. You may also request an update to the company name on your account by having the Team Agent edit the account information.

Please note that you cannot resolve this issue with documentation showing permission to publish this app on behalf of the content owner or institution.

anyone has the same problem or already fix this issues ?
i have publish my app xxxx under my company yyyy and getting rejected. it's weird to push some app that our product


text:
Q: Implementing a vertical seekbar - How to add a new class in Android Studio? I'm trying to implement the vertical seekbar described in this SO answer. I understand that when that answer was written, Eclipse was the standard IDE for Android development, and so it was probably trivial to follow these instructions:

To implement it, create a new class in your project, choosing the
  right package:

However I don't know what this translates to in Android Studio. My menu looks like this:

As you can see, I have the option to create a new C++ class (among many other things), but not a Java class.
What do I need to do in order to make use of the vertical seekbar in Android Studio? I tried creating a new "UI Component" but that brought up a heap of skeleton code and mucked up my UI layout.

A: You have to right click on any SubPackage of main or Main to get create Java class option

A: Do Following Steps

*

*Go to app->src->main->java.

*Right Click On Java Directory Select New->Java Class

A: You need to create the Java class in the correct directory. You need to go to ../src/main/java/your_package_name/ then you can create a new Java class.

A: First of all you need to switch tab from Project to Android.
On that Android File system Select ProjectName -> Java.
Right click on Java and create new Java class. I think it will work for you.
You can create java class from project tab in android studio but thats some what complex file structure as compared to Android File system, so you have to switch to Android tab,On top right of Android studio.
Try this...


text:
Q: How to set different cache sizes for different datasets in h5py? I am currently working on a ML problem, and I have a h5 file that consists of 2 datasets. One is my training data (a dataset with shape of (length, h, w)), and one is the metadata. That is an np.array of json string of shape (length,).
The problem I have is that h5py.File creates a single cache size for all of the datasets. So although my metadata does not need as much caching as my actual data (it is around 2GB, in comparison to my data which is around 60GB), if I declare a caching mechanism, it will be cached with a similar memory footprint compared to the data that is far more important to cache.
So if I declare a 4GB cache for each dataset, I will cache around 0.17 of my dataset and 100% of my metadata which will consume around 6GB of my memory. Is there any way to use a different cache size for my metadata dataset?


text:
Q: With CanCan, limit what roles an admin can assign to self or others through AdminAbility I'm trying to setup a admin role system, where many admins have different roles. I'm starting with two roles, :super_admin and :office_admin.
I want the :office_admin the ability to manage other :office_admins, but not the :super_admins. I've accomplished parts of this idea through the Ability file.
My schema:
class Admin < ActiveRecord::Base
  has_many :admin_assignments
  has_many :admin_roles, :through => :admin_assignments
  attr_accessible :name, :admin_role_ids
end

.
class AdminAssignment < ActiveRecord::Base
  attr_accessible :admin_id, :admin_role_id
  belongs_to :admin
  belongs_to :admin_role
end

.
class AdminRole < ActiveRecord::Base
  has_many :admin_assignments
  has_many :admins, :through => :admin_assignments
  attr_accessible :name
end

.
class AdminAbility
  include CanCan::Ability
  def initialize(admin)
    if admin.role? :super_admin
      can :manage, Admin
    elsif admin.role? :office_admin
      can :manage, Admin, :admin_roles => { :name => ['office_admin'] }
    end
  end
end

My problem is I cannot prevent the office admin assigning himself the role of SuperAdmin. Is this something I can do through CanCan or do I have to push parts of that authorization logic into the ActiveRecord model?


text:
Q: URL request from Python I have a Server running and its always listening to the value field
I can make a requests from a web browser from the URL,
Eg: http://192.168.1.101/value=1

How can i make a request like this from Python, i tried the above code but it doesnt seem to work.
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = 'http://192.168.1.101/value=1'
request = Request(url)

My server is listening in the above formate.(GET)
GET /value=1 HTTP/1.1

Cheers!

A: Use requests module
import requests as req
url = 'http://192.168.1.101/value=1'
resp = req.get(url)
print(resp.text) # Printing response


text:
Q: Use CloudKit to return users records and deny accounts instead of code, have more of a best practice/functionality question regarding CloudKit.  Can't seem to find answers, or maybe just don't understand.
Questions:

*

*When I save the record, cloud kit creates a unique record id, i was thinking of getting that id and storing in core data to allow specific query's on that at a later time vs entire database searches.  However, once I save a record, how do i get the record id that was created?  Is this possible?

*What if I allow a user to report another user for some reason and thereby want to block that user from posting to the cloud until a review can be done. Is there a user access database in the cloud?  if not, thoughts on how to?
Thanks all.

A: By default when you create a CKRecord it will generate a guid as it's ID. You can also specify your own id the moment you create the CKRecord. The it does not need to be a guid. As long as it's unique. Your save action will have a callback where you will get the ID.
Every user has it's own unique id which you can easily get. You could create a table with your blocking information. You only have to query for that yourself to implement the blocking mechanism.


text:
Q: Change default stylus pointer style in android It is possible to capture different stylus events on Android 4.0 and above.
But there does not seem to be a way to change the pointer style to something other than the default, since I want to set a small image dynamically as pointer when the stylus hover event occurs.
I went through the Android motion event API documentation, but I did not find any information about this.
How can this be achieved?

A: I found a solution for Samsung devices.
After digging into SPen SDK sources, I found that it is very easy to change hover icon.
You need to use this function:
public boolean setSPenCustomHoverIcon(Context paramContext, View paramView, Drawable paramDrawable);

You just need to pass: application context, View and Drawable Icon.


text:
Q: PHP - insert button to delete a row from MySQL table I have a site/forum where you can post things. The users can posts on their personal wall. I want to put a delete button for every post in the wall. When i press it to detele the row in table that coresponds to that post. How can i do that?

A: <?php
    $entity = Post::getTheThings($id);
    $entity->deleteMehhhhh();


text:
Q: How to compress multiple images size while uploading imaged using php? Below is my code which I tried but there is showing some warning errors:

Warning: getimagesize(C:\xampp\tmp\php2F0B.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\maahima\admin\uploadBulkImages.php on line 55
Warning: imagejpeg() expects parameter 1 to be resource, string given in C:\xampp\htdocs\maahima\admin\uploadBulkImages.php on line 66

I want the code to insert images in folder in bulk with compressed image.
<?php
if(isset($_FILES['file']['tmp_name'])){
    $pro_image = $_FILES['file']['tmp_name'];
    $no_of_file = count($_FILES['file']['tmp_name']);
    $name = ''; $type = ''; $size = ''; $error = '';

    for($i=0;$i < $no_of_file;$i++){
        if(! is_uploaded_file($_FILES['file']['tmp_name'][$i])){
            header("location:add_products.php?error=er8r5r");
        }
        else{
            if(move_uploaded_file($_FILES['file']['tmp_name'][$i],"../products/".$_FILES['file']['name'][$i])){
                if ($_FILES["file"]["error"][$i] > 0) {
                    $error = $_FILES["file"]["error"];
                }
                else {
                    $image="";
                    $error = "Uploaded image should be jpg or gif or png";
                    $url = '../smallSize-Image/'.$_FILES['file']['name'][$i];
                    echo  $url;
                    $source_url=$_FILES["file"]["tmp_name"][$i];
                    $destination_url=$url;
                    $quality=12;
                    $info = getimagesize($source_url);

                    if ($info['mime'] == 'image/jpeg')
                        $image = imagecreatefromjpeg($source_url);
                    elseif ($info['mime'] == 'image/gif')
                        $image = imagecreatefromgif($source_url);
                    elseif ($info['mime'] == 'image/png')
                        $image = imagecreatefrompng($source_url);

                    imagejpeg($image, $destination_url, $quality);
                    return $destination_url;

                    $buffer = file_get_contents($url);
                    /* Force download dialog... */
                    //header("Content-Type: application/force-download");
                    //header("Content-Type: application/octet-stream");
                    //header("Content-Type: application/download");
                    // header("location:add_products.php?succcess=s8sc5s");
                    /* Don't allow caching... */
                    //  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    /* Set data type, size and filename */
                    //header("Content-Type: application/octet-stream");
                    //header("Content-Length: " . strlen($buffer));
                    //header("Content-Disposition: attachment; filename=$url");
                    /* Send our file... */
                    echo $buffer;
                }
            }
            else{
                header("location:add_products.php?error=er8r5r");
            }
        }
    }
}
else{
}
?>

A: Your script has a lot of illogical features. If you are going to redirect, you need to exit. You should not have a return in the middle of the script, that is somewhat random (probably this is unfinished script and it's inside another function/method?). Here are some things I would do if I were to do this.
If you don't already have a config that has some absolute defines, I would create one and include it on every initial load page at the top.
This is tested and works, provided it's implemented correctly and as demonstrated. Use some of it, bits of it, or none of it, but it does work:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('UPLOAD_DIR',ROOT_DIR.DS.'uploads'.DS.'images');
define('THUMB_DIR',ROOT_DIR.DS.'uploads'.DS.'thumbs');
define('VENDOR_DIR',ROOT_DIR.DS.'vendors');

I would consider making some quick functions, in this case a class/method system to complete some simple tasks.
/vendors/Files.php
class Files
    {
        /*
        ** @description This will turn a numbered $_FILES array to a normal one
        */
        public  static  function normalize($key = 'file')
            {
                foreach($_FILES[$key]['tmp_name'] as $fKey => $value) {
                    $FILES[]    =   array(
                        'tmp_name'=>$_FILES[$key]['tmp_name'][$fKey],
                        'name'=>$_FILES[$key]['name'][$fKey],
                        'error'=>$_FILES[$key]['error'][$fKey],
                        'size'=>$_FILES[$key]['size'][$fKey],
                        'type'=>$_FILES[$key]['type'][$fKey]
                    );
                }

                return $FILES;
            }
        /*
        ** @description I would contain this step into an editable method for
        **              ease of use and reuse.
        */
        public  static  function compress($path, $dest, $quality = 12)
            {
                $info   =   getimagesize($path);

                if($info['mime'] == 'image/jpeg')
                    $image  =   imagecreatefromjpeg($path);
                elseif($info['mime'] == 'image/gif')
                    $image  =   imagecreatefromgif($path);
                elseif($info['mime'] == 'image/png')
                    $image  =   imagecreatefrompng($path);

                imagejpeg($image,$dest,$quality);
            }
    }

Put it all together, in this case I would maybe throw exceptions and save errors to a session. Loop through them on the add_products.php page.
# Add our config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Add our file handler class (spl_autoload_register() is a better option)
include(VENDOR_DIR.DS.'Files.php');
# Observe for file upload
if(!empty($_FILES['file']['tmp_name'])){
    # Use our handy convert method
    $FILES      =   Files::normalize();
    # Try here
    try {
        # Loop through our normalized file array
        foreach($FILES as $i => $file){
            # Throw error exception here
            if(!is_uploaded_file($file['tmp_name']))
                throw new Exception('File is not an uploaded document.');
            # I like to add a create directory line or two to cover all bases
            if(!is_dir(UPLOAD_DIR)) {
                if(!mkdir(UPLOAD_DIR,0755,true))
                    throw new Exception('Upload folder could not be created.');
            }
            # Ditto
            if(!is_dir(THUMB_DIR)) {
                if(!mkdir(THUMB_DIR,0755,true))
                    throw new Exception('Thumb folder could not be created.');
            }
            # Create an absolute path for the full size upload
            $path   =   UPLOAD_DIR.DS.$file['name'];
            # If no errors and file is moved properly, compress and save thumb
            if(($file["error"]) == 0 && move_uploaded_file($file['tmp_name'],$path))
                # Create a thumbnail from/after the file you moved, not the temp file
                Files::compress($path,THUMB_DIR.DS.$file['name']);
            # Throw error on fail
            else
                throw new Exception('An unknown upload error occurred.');
        }
    }
    # Catch, assign, redirect
    catch (Exception $e) {
        $_SESSION['errors'][]   =   $e->getMessage();
        header("location: add_products.php?error=er8r5r");
        exit;
    }
}


text:
Q: "Xcode" is damaged and can't be opened. You should move it to the Trash Installed XCode 6 on Mavericks. It din't run. Updated OS to Yosemite 10.10 : Now Xcode.app (installed through *.dmg) launch fails with error message "Xcode" is damaged and can't be opened. You should move it to the Trash. Updated to XCode 6.0.1 through App Store. Still no luck. Same error message. Anyone with a fix?

A: Some times in below options

*

*Open System Preferences

*Click on "Security & Privacy"

Allow apps downloaded from contains only 2 options "Anywhere" is missing for that open your terminal and add below line
sudo spctl --master-disable

enter your system password. Now you quit System Preferences and reopen it System Preferences/Security & Privacy/General now "Anywhere" option will be there. Hurrah You have done it.
 hope it will work for you.

A: I know this is an older question, but if you're like me and absolutely want to install Xcode from a DMG and not from the App Store, there is a way, inspired by this post from Will Lowe that talks about installing an un-signed application.

*

*Install the DMG as usual (Double-click, Drag-n-drop)

*Open System Preferences

*Click on "Security & Privacy"

*Adjust the "Allow applications downloaded from:" setting to "Anywhere"

*Open Xcode

*Be patient while it verifies and opens

You only need to do this the first time you open Xcode, so you can change your Security settings back to their original value after Xcode has fully launched.

A: I experienced this error with any new added application under (all) macOS Sierra builds.
The only solution that worked for me was to execute :
xattr -rc /Applications/<faulty application>.app

You can also use the following command to "repair" all applications :
xattr -rc /Applications/*.app

A: If you trust the people from whom you are downloading things you can bypass the warning by adjusting your 'Preferences > Security & Privacy' to
Allow applications downloaded from: Anywhere

A: I have just experienced this with Xcode 6.1.1 on Yosemite, except it only happened when I build and run in the simulator - on app launch Xcode would crash and a panel would declare "Xcode is damaged. Delete it and download again from the App Store".
I did all of the following to solve it:

*

*Delete derived project data and full clean

*Delete app from simulator and quit simulator

*Reboot

Anyway just in case this helps a new visitor to this question :)

A: I found this solution helpful and follow these steps:

*

*run this command into terminal sudo spctl --master-disable it may ask your user password.

*go to System Preferences -> security and privacy -> general tab -> check Anywhere option on bottom.

Hope it helps someone.


text:
Q: I am trying to use the KeyDown Event but nothing happens If anyone can help me figure out what is wrong with this, my goal is to press F1/F2 and let the button be pressed without clicking on it, the form is always on top so it should work, even when i click on the form and do it within the form is does not work.
Private Sub saveBtn_KeyDown(sender As Object, e As KeyEventArgs) Handles saveBtn.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                saveBtn.PerformClick()
        End Select
    End Sub

    Private Sub save2_KeyDown(sender As Object, e As KeyEventArgs) Handles save2.KeyDown
        Select Case e.KeyCode
            Case Keys.F2
                save2.PerformClick()
        End Select
    End Sub

A: You can also trap F1/F2 by overriding ProcessCmdKey() for the Form.
Just add this to the forms code:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Select Case keyData
        Case Keys.F1
            saveBtn.PerformClick()

        Case Keys.F2
            save2.PerformClick()

    End Select
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

A: it will not work because you assigned the event to the button it will only work if the button is focused like selecting it with the tab key
what you should do is assign your code with the Window_PreviewKeyDown event
In the designer, set the KeyPreview property of your form to True. Then handle the form_KeyDown event, and check there if the F1/2 key was pressed.. The KeyPreview property of your form triggers the key events first on the form, and then on any control it was actually pressed
your code should be somthing like this
' look at the part of  Handles Me.PreviewKeyDown
Private Sub MainWindow_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.PreviewKeyDown
    Select Case e.Key
        Case Key.F1
            Me.Title = "F1 Key Down"
             saveBtn.PerformClick()
        ' Button1_Click(Nothing, Nothing)
        Case Key.F2
            save2.PerformClick()
        Case Key.S
            Me.Title = "S Key Down"
            e.Handled = True ' if your courser on a text box this will prevent it from getting the S keystroke
        Case Else
            Me.Title = "Another Key Down"
    End Select
End Sub


text:
Q: Different behaviour in redactors regarding code .open .close files with Python So, when I try to execute the following code, the behaviour of two IDE's are different.
In PyCharm the code is executing and creates a file with an input inside.
todos = []
todo = input("Enter a todo: ") + "\n"
todos.append(todo)
file = open('todos.txt', 'w')
file.writelines(todos)

But in Thonny IDE the code is executing without any errors:
todos = []
todo = input("Enter a todo: ") + "\n"
todos.append(todo)
file = open('todos.txt', 'w')
file.writelines(todos)

The file is still created, but the input is not inside, till I put a new following command:
file.close()

Why do they behave different? Is it not dependant of interpreter than of IDE's?

A: No matter the IDE if you use open the responsibility to close the file is on you and you shouldn't rely on any IDE behaviour for that.
To be safe you should use context managers with open syntax in order to shift the responsibility for closing the file to the interpreter.
Here's a deeper explanation:
https://realpython.com/python-with-statement/#the-with-statement-approach


text:
Q: Multiple instances of a class with constant variables use same memory for constants? If I have a class that defines multiple constant variables like so...
class SomeClass {
public:
    SomeClass() : SOME_CONSTANT(20), ANOTHER_CONSTANT(45), ANOTHER_CONSTANT2(25), ANOTHER_CONSTANT2(93) { }

private:
    const int SOME_CONSTANT;
    const int ANOTHER_CONSTANT;
    const int ANOTHER_CONSTANT2;
    const int ANOTHER_CONSTANT3;

Will multiple instances of this class be optimized to point to the same memory for the constants? or can I save memory by making each constant static?

A: If they are not static, then no, they will not be optimized out. Each instance will have space for all the constants. (In fact, I don't think the compiler is even allowed to combine them in any way.)
If you do declare them static, they are in global memory and not in each instance. So yes, it will use less memory.
EDIT:
If you want to make them static constants, it should be done like this:
class SomeClass {
    public:
        SomeClass(){ }

    private:
        static const int SOME_CONSTANT;
        static const int ANOTHER_CONSTANT;
        static const int ANOTHER_CONSTANT2;
        static const int ANOTHER_CONSTANT3;

};

const int SomeClass::SOME_CONSTANT     = 20;
const int SomeClass::ANOTHER_CONSTANT  = 45;
const int SomeClass::ANOTHER_CONSTANT2 = 25;
const int SomeClass::ANOTHER_CONSTANT3 = 93;

A: How about an enumeration instead?
class SomeClass {
public:
    SomeClass() { }

private:
    enum {
        SOME_CONSTANT = 20,
        ANOTHER_CONSTANT = 45,
        ANOTHER_CONSTANT2 = 25,
        ANOTHER_CONSTANT3 = 93
    };
};

An enumeration guarantees that the constants won't take up any memory at all.

A: Declared this way, all instances of this class will have its own copies. To avoid this and save memory, declare them as static.
Note: don't forget to define them outside the class. As these are ints, you may avoid defining them outside the class, this actually depends more on the compiler, than the standard (yes, I know how ridiculous this soudns). I can't test it now, but I remember, that gcc and VS have different behaviors about this.
So, you may need to do this:
class SomeClass {
public:
    SomeClass()
    { }

private:
    static const int SOME_CONSTANT;
    static const int ANOTHER_CONSTANT;
    static const int ANOTHER_CONSTANT2;
    static const int ANOTHER_CONSTANT3;

const int SomeClass::SOME_CONSTANT = 20;
//.. the same for the others.

EDIT I'll find this part of the standard (the exception for integral types) and post it here + tests on both compilers later today :) )

A: You cannot make those constants static - simply because your constructor initialses them!
SomeClass() : SOME_CONSTANT(20), ANOTHER_CONSTANT(45), ANOTHER_CONSTANT2(25), ANOTHER_CONSTANT2(93) { }

Remove those initialisers i.e.
SomeClass{};
static const int SOME_CONSTANT = 20;

Then you will have just one int for the class.

A: You can try checking the sizeof() of an instance of the class. I don't think they'll be optimized out. Using const static variables for this purpose will probably be the right thing to do, especially if they are all integers, in which case you can initialize them at the definition and get compile time constants without worrying about static objects initialization order.
class SomeClass
{
private:
    const static int SOME_CONSTANT     = 20;
    const static int ANOTHER_CONSTANT  = 45;
    const static int ANOTHER_CONSTANT2 = 25;
    const static int ANOTHER_CONSTANT3 = 93;
};


text:
Q: How to expand height of Column wrapped by SingleChildScrollView properly I wanted to make a login form where the fields will be in a column of a specific width.
I wanted to be able to scroll the entire page when the window size is smaller.
import 'package:flutter/material.dart';
class LoginPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
    resizeToAvoidBottomInset: false,
    backgroundColor: Colors.blue,
    body: SingleChildScrollView(
      child: Center(
        child: Container(
          // height:  MediaQuery.of(context).size.height ,
          width: 500,
          decoration: BoxDecoration(
              color: Color(0xfffee6dc),
              border: Border.all(
                  width: 0,
                  style: BorderStyle.none
              ),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Column(
            children: [
              Text("TEST"),
              SizedBox(height: 50,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
              TextFormField(),
              SizedBox(height: 10,),
            ],
          ),
        ),
      ),
    ));
}
}

This works, but when I maximize the window, the height of the container doesn't adjust to the size of the window, only to its children:

When I set the height to: MediaQuery.of(context).size.height
i's better,  but now when i shrink the window it throws me an error:
A RenderFlex overflowed by ** pixels on the bottom.

A: If you like to adjust the height, it should be on top widget constraints .

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.blue,
        body: Center(
          child: Container(
            alignment: Alignment.topCenter,
            constraints: BoxConstraints.tight(Size.fromWidth(600)),
            decoration: BoxDecoration(
              color: Color(0xfffee6dc),
              border: Border.all(width: 0, style: BorderStyle.none),
              borderRadius: const BorderRadius.all(
                Radius.circular(20),
              ),
            ),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("TEST"),
                  for (int i = 0; i < 10; i++) ...[
                    TextFormField(),
                    SizedBox(
                      height: 10,
                    ),
                  ],
                ],
              ),
            ),
          ),
        ));
  }
}

A: you need to create new class name sizeconfig
Code of sizeconfig Class:
import 'package:flutter/material.dart';

class SizeConfig {
  static MediaQueryData? _mediaQueryData;
  static double? screenWidth;
  static double? screenHeight;
  static double? defaultSize;
  static Orientation? orientation;
  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData?.size.width;
    screenHeight = _mediaQueryData?.size.height;
    orientation = _mediaQueryData?.orientation;
    defaultSize = orientation == Orientation.landscape
        ? screenHeight! * 0.024
        : screenWidth! * 0.024;
  }
}

Now you need to call this call inside build method:

Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(

Now its Work Fine
**This is your Actual Class Code:**
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'confriguration/size_config.dart';
class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.blue,
        body: Container(
          color:Colors.redAccent,
          child: SingleChildScrollView(
            child: Center(
              child: Container(
                // height:  MediaQuery.of(context).size.height ,
                width: SizeConfig.screenWidth! * 0.9,
                decoration: BoxDecoration(
                    color: Color(0xfffee6dc),
                    border: Border.all(
                        width: 0,
                        style: BorderStyle.none
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(20))),
                child: Column(
                  children: [
                    Text("TEST"),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01,),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                    TextFormField(),
                    SizedBox(height: SizeConfig.screenHeight! * 0.01),
                  ],
                ),
              ),
            ),
          ),
        ));
  }
}

Here is video link


text:
Q: OS X from Carbon to Cocoa window creation? Edit: This question has been answered indirectly in the comments (using GLUT to avoid the need for either) but because its not posted as an answer, I cannot "accept" it although my issue is solved.
I have a cross platform OpenGL application, written in C++, that (on Mac OS X) uses Carbon for the window creation and message pump (Think...NeHe Lesson 1).  Recent changes to my code utilizing C++11 features has made it incompatible with the GCC that comes bundled with XCode.
All of my attempts to use systems like MacPorts, HomeBrew, etc... have failed for different reasons (Mostly due to my need to compile 32bit for Carbon support).  I was originally going to ask if anyone had a better solution for installing an updated G++ in Mac OS X 10.8.
That seems like a short sighted solution (at some point, I will need to upgrade to Cocoa and 64bit) so my question has evolved to asking what would be the most simple way to have my existing (very large) application utilize Cocoa for this task rather than Carbon?
I have all of the "Carbon Code" in its own separate .cpp/.h file, which has only two functions, one to create an OpenGL window, and one that is a message pump that uses ReceiveNextEvent.

Edit:
To be clearer, I am looking for the best way to design (more or less) a drop in replacement for my existing Carbon window creation, and message pump functions, but in Cocoa.  I understand that being a different API, using different language concepts, that a simple one to one command replacement will not suffice.  My existing code has a source code file for Mac that has two functions which perform core tasks (with Carbon) that I call, InitWindow, and DoEvents.  These create the window, and cycle through the pending events respectively.  It is my goal to replace this source code file with one that uses Cocoa, exposing the same functions so there is little to no modification of my core code.
What would be the best way to achieve my goal?  I am not familiar with Cocoa and Obj-C is alien to me.

A: Going to Cocoa 64-bit definitely sounds like a great idea. And I recommend using some of the native UI if you want to make your users happy, too.
The easiest thing to do would be to create an NSWindow with an NSOpenGLView in it. You can either do that in Interface Builder, or in code. It's probably best to do it by creating a new Cocoa app using Xcode's template (File > New Project > Cocoa App). That will give you a window by default. You can open it in Interface Builder and add an NSOpenGLView to it. You can make the view a custom subclass of NSOpenGLView, and add your event handling to it. See the docs for NSResponder for more information on how Cocoa dispatches events.


text:
Q: How to avoid multiple scroll events in virtualisation in angular grid? I have a grid control written in angular, it has implement Virtualization.
The Virtualization is implemented as following.

*

*load the first 60 records in the grid on initial load.

*every time user scrolls down load another 60 records.

*the records to be loaded are decided by the scrollTop position if the scroll.

My solution has the following issues:

*

*when we load the records in scroll down, as new rows are loaded in the grid, scroll events is fired for each loaded row.

*by this, it triggers 60 scroll events, on each scroll, and this causes the chaining of the scroll events.

*so in the end, the page is scrolled till the end of the screen.

How can I fix this?