text:
Q: Find custom type in Object I have a Upload class with different properties and I like to find each UploadObject property in this class or inside of other propertys. How can i find all UploadObjects in my Upload class?
class UploadObject
{
    public string ID {get; set;}
    //...
}

class PicUpload
{
    UploadObject Pic {get; set;}
    //...
}

class FileUpload
{
    UploadObject File {get; set;}
    //...
}

class Upload
{
    //..
    FileUpload File {get; set;}
    List<PicUpload> Pics  {get; set;}
    //...
    UploadObject Something {get; set}
}

Edit:
I'm searching for a function like:
public object[] FindProperties(object objectTree, Type targetType) {}

A: typeof(Upload).GetProperties()
   .Where(p => typeof(UploadObject).IsAssignableFrom(p.PropertyType));

will return all properties where the return type is UploadClass or inheriting class. Then you would have use recursion on it with a stop condition on types that can't possibly contain an UploadObject. The stop condition could be to check if the return type is a primitive type using IsPrimitive (available on Type).
You can replace the IsAssignableFrom with == typeof(UploadObject) if you just want that specific type.
Edit:
This is the idea I had in mind. Disclaimer: The only testing I have done is to compile it and run it against one scenario, for which it worked, but it illustrates the idea.
public static T[] GetAllPropertyValuesForTypeinTree<T>(object rootObject)
{
    var propertyInfos = rootObject.GetType().GetProperties();
    var withCorrectPropertyType = propertyInfos
        .Where(p => p.PropertyType == typeof(T)).ToList();

    var withListsOfType = propertyInfos.Where(p =>
        IsEnumerableOf<T>(p.PropertyType)).ToList();
    var complexProperties = propertyInfos.Except(
         withCorrectPropertyType.Concat(withListsOfType))
         .Where(p => !p.PropertyType.IsPrimitive && !p.PropertyType.IsGenericType);

    var complexValues = new List<T>();
    foreach (var complexProperty in complexProperties)
    {
         complexValues.AddRange(GetAllPropertyValuesForTypeinTree<T>(
             complexProperty.GetValue(rootObject, null)));
    }

    var listValues = withListsOfType.Select(p =>
        (IEnumerable)p.GetValue(rootObject, null))
        .SelectMany(p => p.OfType<T>());
    var propertyValues = withCorrectPropertyType.Select(p =>
        (T) p.GetValue(rootObject, null));
    return propertyValues.Concat(listValues).Concat(complexValues).ToArray();
}

private static bool IsEnumerableOf<T>(Type type)
{
    if (!typeof (IEnumerable).IsAssignableFrom(type))
        return false;

    return type.GetInterfaces().Any(interfaceType => interfaceType.IsGenericType
        && (interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
        && type.GetGenericArguments()[0] == typeof(T)))
        || type == typeof(IEnumerable<T>);
 }

You would call it with:
var propVals = GetAllPropertyValuesForTypeinTree<UploadObject>(theInstance);

A: Are you looking for something like this?
typeof(UploadClass).GetProperties().Where(x => x.PropertyType == typeof(UploadObject));


text:
Q: How to alter Foreign Key reference ON DELETE CASCADE without dropping table I have created database tables with foreign key reference ON UPDATE CASCADE ON DELETE RESTRICT . However, I set my engine MyISAM so this reference does not work. The primary key is being deleted even if it is used elsewhere as foreign key. How can I fix this issue?
I tried to alter table engine to InnoDB, but even if it is set to InnoDB the foreign references does not work. Moreover, I tried to drop one empty table with foreign key reference and engine MyISAM. Then I tried to add that table, but it does not add. Most probably when I drop table foreign references remain somewhere in schemas.
My query to create table.
CREATE TABLE IF NOT EXISTS `products` (
    `productid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `productname` varchar(255) NOT NULL,
    `productcode` varchar(255) NOT NULL,
    `producttype` varchar(255) NULL
)
ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `sales` (
    `salesid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY
    `productid` int(10) NOT NULL,
    `quantity` int(10) NOT NULL,
    `price` int(10) NOT NULL,
    `date` datetime NOT NULL,
    CONSTRAINT `fk_sales_productid`
    FOREIGN KEY (productid)
    REFERENCES products(productid) ON UPDATE CASCADE ON DELETE RESTRICT
)
ENGINE=MyISAM DEFAULT CHARSET=utf8;

These 2 tables were created with this query as MyISAM. They have data on it which i need.
I run this query to change engine to InnoDB as reference on delete cascade were not working in MyISAM. 'ALTER TABLE products ENGINE=InnoDB;' 'ALTER TABLE sales ENGINE=InnoDB;'
But after making them InnoDB, the reference still does not work when I delete product, related productid in sales table becomes NULL.

A: As per P.Salmon's demo queries seems valid. You probably missing something in FK references. I suggest you to export 2 tables, the examine it in editor, especially FK references part and make sure engine is InnoDB as it has row-level locking and has what is called referential integrity that involves supporting foreign keys and relationship constraints.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find all vectors so that a vector equation can be solved? Unfortunately, my text book doesn't clarify this process at all.  It's asking to find all all vectors [a b] so that the vector equation can be solved.  The vector equation is:
$c1$ $[3,1]$ + $c2 [6,2]$=$[a, b]$
The linear system would look like:
$3c1+6c2=a$
$c1+2c2=b$
My text doesn't give any indication how to solve this and I'm stuck.  Any help would be appreciated!  Also, apologies since I can't get the vector forms inserted properly!

A: Hint:
You have two equations, and two variables (we treat a, b as constants). Set up the associated augmented coefficient matrix, row reduce, and solve for $c_1, c_2$, which can each be expressed as functions of $a, b$. From that, you should also be able to express $a, b$ as functions of the constants $c_1, c_2$.
Associated augmented coefficient matrix to your system of equations:
$$\begin{pmatrix} 3 & 6 &\mid& a\\ 1 & 2 & \mid & b\end{pmatrix}$$
TIP: Be sure to choose a value for $b$ that will ensure the system is consistent.


text:
Q: invalid literal for int() with base 10: '' error with only numbers I know what the error is, but why would it display this error if there are no other characters? I know this question has been asked but I can't find a reason for it.
error line code:
Traceback (most recent call last):
File "C:/Users/tudor/Documents/python/custom cypher/cypher.py", line 179, in
<module>
array0, array1, array2 = (int(crypt_array0) // array0_key),
(int(crypt_array1) // array1_key), (int(crypt_array2) // array2_key)
ValueError: invalid literal for int() with base 10: ''

full code:
import random
import itertools
print ('''
         READ THIS BEFORE USE

    This encryption can ONLY use ASCII
    this contains most/all of the
    keys on your keyboard, this
    includes capital letters

    The key supports around 100000 digits.

    The hard encoding adds three more
    layers of security. You will have to
    copy your new key.

    ''')

hard_encoding_1 = {
'0': '8',
'1': '4',
'2': '3',
'3': '7',
'4': '1',
'5': '9',
'6': '5',
'7': '6',
'8': '2',
'9': '0',
}

hard_encoding_2 = {
'0': '5',
'1': '9',
'2': '0',
'3': '1',
'4': '4',
'5': '3',
'6': '7',
'7': '2',
'8': '6',
'9': '8',
}

hard_encoding_3 = {
'0': '2',
'1': '5',
'2': '7',
'3': '4',
'4': '9',
'5': '8',
'6': '1',
'7': '0',
'8': '3',
'9': '6',
}

hard_encoding_4 = {
'0': '1',
'1': '3',
'2': '5',
'3': '8',
'4': '0',
'5': '7',
'6': '6',
'7': '2',
'8': '9',
'9': '4',
}

def randint_generator(n):
    key_generate = ''
    for b in range(n):
        b = random.randint(0, 9)
        key_generate = key_generate + str(b)
    return 'copy this key: ' + key_generate

def setnumber(x, y, str_or_int):
    n = len(str(x))
    z = str(x)
    while n != y:
        z = '0' + z
        n = len(z)
    if str_or_int == str:
        return str(z)
    if str_or_int == int:
        return int(z)

while True:
    What_operation = int(input('''
        Do you want to:
        soft:
            decrypt(0)
            encrypt(1)
        hard:
            decrypt(3)
            encrypt(4)
        generate a key:
            100-digit(5)
            500-digit(6)
            1,000-digit(7)
            10,000-digit(8)
            1,000,000-digit(9)
            '''))

if What_operation == 1:
    text = input('What is your text you want to convert? ')
    New_text = bin(int.from_bytes(text.encode(), 'big'))
    key = int(input('What is your key you want to use?'))
    cyphered_text = int(New_text[2:]) * key
    print ('copy this text: ', cyphered_text)

if What_operation == 0:
    numbers = input('What is your string you want to convert? ')
    key = int(input('What is your key? '))
    New_text = '0b' + str(int(numbers) // key)
    encoded = int(New_text,2)
    decoded = encoded.to_bytes((encoded.bit_length() + 7) // 8,
'big').decode()
    print ('Here is your message: ' + decoded)

if What_operation == 4:
    text = input('What is your text you want to convert? ')
    New_text = bin(int.from_bytes(text.encode(), 'big'))
    key = int(input('What is your key you want to use?'))
    key_2 = random.randint(1,4)
    cyphered_text = New_text[2:]
    hard_cyphered_text = ''
    cyphered_text = int(cyphered_text) * key
    for i in str(cyphered_text):
        if key_2 == 1:
            hard_cyphered_text = hard_cyphered_text + hard_encoding_1[i]
        if key_2 == 2:
            hard_cyphered_text = hard_cyphered_text + hard_encoding_2[i]
        if key_2 == 3:
            hard_cyphered_text = hard_cyphered_text + hard_encoding_3[i]
        if key_2 == 4:
            hard_cyphered_text = hard_cyphered_text + hard_encoding_4[i]
    x_cyphered_text = str(hard_cyphered_text)
    array0 = ''
    array1 = ''
    array2 = ''
    count = 0
    for i in x_cyphered_text:
        if count % 3 == 0:
            array0 += i
        count += 1
    count = 0
    for i in x_cyphered_text:
        if count % 3 == 1:
            array1 += i
        count += 1
    count = 0
    for i in x_cyphered_text:
        if count % 3 == 2:
            array2 += i
        count += 1
    array0_key, array1_key, array2_key = random.randint(1, 99999999),
    random.randint(1, 99999999), random.randint(1, 99999999)
    final_array0, final_array1, final_array2 = int(array0) * array0_key,
    int(array1) * array1_key, int(array2) * array2_key
    len_array0, len_array1, len_array2 = str(len(str(final_array0))),
    str(len(str(final_array1))), str(len(str(final_array2)))
    full_key = str(key) + str(key_2) + setnumber(len_array0, 6, str) +
    setnumber(len_array1, 6, str) + setnumber(len_array2, 6, str) +
    setnumber(array0_key, 8, str) + setnumber(array1_key, 8, str) +
    setnumber(array2_key, 8, str)
    complete_cyphered_text = str(final_array0) + str(final_array1) +
    str(final_array2)
    print('copy this text: ', complete_cyphered_text)
    print('Copy your key: ', full_key)

if What_operation == 3:
    numbers = input('What is your string you want to convert? ')
    key = input('What is your given key? ')
    key_2 = int(key[-43:-42])
    array2_key, array1_key, array0_key = int(key[-8:]), int(key[-16:-8]),
    int(key[-24:-16])
    len_array2, len_array1, len_array0 = int(key[-30:-24]),
    int(key[-36:-30]), int(key[-42:-36])
    n0, n1, n2 = len_array0, len_array1, len_array2
    crypt_array0, crypt_array1, crypt_array2 = numbers[:n0], numbers[n0:n1],
    numbers[n0 + n1:]
    array0, array1, array2 = (int(crypt_array0) // array0_key),
    (int(crypt_array1) // array1_key), (int(crypt_array2) // array2_key) ###
    numbers_noncrypt = ''.join(''.join(x) for x in
    itertools.zip_longest(str(array0), str(array1), str(array2),
    fillvalue=''))
    key = int(str(key)[:-43])
    encoded_text = ''
    decoding = {}
    if key_2 == 1:
        decoding = {a: b for b, a in hard_encoding_1.items()}
    if key_2 == 2:
        decoding = {a: b for b, a in hard_encoding_2.items()}
    if key_2 == 3:
        decoding = {a: b for b, a in hard_encoding_3.items()}
    if key_2 == 4:
        decoding = {a: b for b, a in hard_encoding_4.items()}
    for i in str(numbers_noncrypt):
        encoded_text = encoded_text + decoding[i]
    encoded_text = '0b' + str(int(encoded_text) // key)
    encoded = int(encoded_text, 2)
    decoded = encoded.to_bytes((encoded.bit_length() + 7) // 8,
    'big').decode()
    print ('Here is your message: ' + decoded)

if What_operation == 5:
    print(randint_generator(100))
if What_operation == 6:
    print(randint_generator(500))
if What_operation == 7:
    print(randint_generator(1000))
if What_operation == 8:
    print(randint_generator(10000))
if What_operation == 9:
    print(randint_generator(1000000))

By the way, the // is not a comment, it is division in python to output in integers and not float, also the code looks crowded as there is a limit on how long the lines have to be on this website. I will put ### to the error line refers to.
I tried debugging it and approaching it in a different way but I can't find a reason why it would do this.

A: Just to get your debugging going, you're trying to convert an empty string into an integer. To see where this is going wrong, you might want to split up:
array0, array1, array2 = (int(crypt_array0) // array0_key),
(int(crypt_array1) // array1_key), (int(crypt_array2) // array2_key) ###

to:
array0 = (int(crypt_array0) // array0_key)
array1 = (int(crypt_array1) // array1_key)
array2 = (int(crypt_array2) // array2_key)

This way it's easier to follow what exactly is going wrong. Also, please only post the appropriate code in the future.


text:
Q: git clone+pull from a different repo on the same machine: Can i specify a filesystem path, or will it still only work with a ssh path? The title pretty much covers the question. I actually had to generate an ssh key in order to get the local-checkout going. Something like this: git clone ec2-user@localhost:/home/ec2-user/local_bare_repo.git local_normal_repo
According to git doc,

<repository> The "remote" repository that is the source of a fetch or
  pull operation. This parameter can be either a URL (see the section
  GIT URLS below) or the name of a remote (see the section REMOTES
  below).

A: If you're already looking at the docs, why didn't you read the section on "Git URLs" as referred in your quote?

For local repositories, also supported by Git natively, the following syntaxes may be used:
/path/to/repo.git/
file:///path/to/repo.git/


text:
Q: How to get error message of Passport.js authentication strategy? Authenticate method of passport.js is using specified authentication strategy to authenticate.
It should be as simple as in the example from documentation:
app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  });

in particular I'm trying to employ wsfed-saml2 strategy to connect with ADFS server:
router.post('callbackPath',
    passport.authenticate('wsfed-saml2', {
      failureFlash: true,
      failureRedirect: 'somePath'
    }),
  function onSuccessfulAuthentication(req, res, next) {
    res.redirect('/')
  })

In my case strategy fails to authorize successfully. However server is sending XML with data of the authenticated user properly. It seems that strategy is somehow unable to parse it.
Is there any way to get detailed error message from executed strategy? At this moment the only thing which happens is error redirection.
With slightly different configuration I've got following stack trace:
TypeError: req.flash is not a function
    at allFailed (C:\inetpub\wwwroot\webapi\node_modules\passport\lib\middleware\authenticate.js:131:15)
    at attempt (C:\inetpub\wwwroot\webapi\node_modules\passport\lib\middleware\authenticate.js:180:28)
    at WsFedSaml2Strategy.strategy.fail (C:\inetpub\wwwroot\webapi\node_modules\passport\lib\middleware\authenticate.js:297:9)
    at C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\strategy.js:225:32
    at C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\samlp.js:363:20
    at Samlp.ignoreValidationFunction (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\samlp.js:30:10)
    at C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\samlp.js:343:12
    at Samlp.ignoreValidationFunction (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\samlp.js:30:10)
    at Samlp.validateSamlResponse (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\samlp.js:338:10)
    at loaded (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\strategy.js:224:21)
    at NullStore.verify (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\state\null.js:9:3)
    at verifyState (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\strategy.js:158:26)
    at executeSamlp (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\strategy.js:244:7)
    at WsFedSaml2Strategy.authenticate (C:\inetpub\wwwroot\webapi\node_modules\passport-wsfed-saml2\lib\passport-wsfed-saml2\strategy.js:289:5)
    at attempt (C:\inetpub\wwwroot\webapi\node_modules\passport\lib\middleware\authenticate.js:361:16)
    at authenticate (C:\inetpub\wwwroot\webapi\node_modules\passport\lib\middleware\authenticate.js:362:7)
    at Layer.handle [as handle_request] (C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\layer.js:95:5)
    at C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\inetpub\wwwroot\webapi\node_modules\express\lib\router\index.js:335:12)

But it also doesn't say what exactly is wrong with response. It just indicates that the response is somehow unacceptable for the wsfed-saml2 strategy.
How can I get more detailed error message when passport's strategy fail?


text:
Q: Why does my program return zeros only? I am working on this code for a summer course so I don't have to take the introductory technology course at school.
public class Family {
   public static void main(String[] args) throws IOException {
      String token = "";
      int counter = 0, boyBoy = 0, boyGirl = 0, girlGirl = 0;
      double ratioBB = 0.0, ratioBG = 0.0, ratioGG = 0.0;

      Scanner inFile = new Scanner(new File("MaleFemale.txt"));
      DecimalFormat df = new DecimalFormat("#.##");

      while (inFile.hasNextLine()) {
         counter++;
         token = inFile.nextLine( );
              if(token.equals("BB")) boyBoy++;
         else if(token.equals("BG") || token.equals("GB")) boyGirl++;
         else girlGirl++;
      }

      ratioBB = (boyBoy / counter) * 100;
      ratioBG = (boyGirl / counter) * 100;
      ratioGG = (girlGirl / counter) * 100;
      df.format(ratioBB);
      df.format(ratioBG);
      df.format(ratioGG);

      System.out.println("Sample Size: " + counter);
      System.out.println("Two Boys: " + ratioBB);
      System.out.println("Boy and Girl: " + ratioBG);
      System.out.println("Two Girls: " + ratioGG);
    }
}

However, whenever I run the program with the accompanying text file (see spoiler below), the last three print statements always return zero. What is going on here?
Here is a sample of the file being read in:
MaleFemale.txt
GB
BG
BG
GG
GB
GB
GB
GB
BG
BG
GB
GG
BG
BG
GG
....

The real text file is 150000 of these types of entries, would the amount of data have anything to do with this? Thank you so much.

A: You are performing integer division in Java, and that must result in another integer.  So, unless they are all boys or all girls, "anything less than counter" divided by "counter" yields 0.
Cast one of them to double to force floating-point arithmetic.
ratioBB = ((double) boyBoy / counter) * 100;

You can do the same for the other divisions in the lines following that line.
You are also ignoring the String output of df.format each time you use it.  Use the return value; it doesn't change the number inputted into it.
System.out.println("Two Boys: " + df.format(ratioBB));  // likewise for more lines

A: Your problem lies here:
int boyBoy = 0, boyGirl = 0, girlGirl = 0, counter = 0;

ratioBB = (boyBoy / counter) * 100;
ratioBG = (boyGirl / counter) * 100;
ratioGG = (girlGirl / counter) * 100;

Since all the variables involved are integers, the comptuation of (boyBoy / counter) will return an integer, rounded down. Because boyBoy / counter is  guaranteed to be less than 1, it rounds down to 0.
Instead, try casting the integers to doubles before dividing, as these will return the actual ratio. Then, instead of multiplying by 100, multiply by 100.0, as multiplication by 100 will also cast to an integer.
ratioBB = ((double) boyBoy / counter) * 100.0;

The first expression is cast to a double, and the multiplication also casts to a double. The other way around, you'll run into this problem.
These are called implicit casts, and over time, you'll learn to watch out for them.

A: When you divide an int by an int (boyBoy / counter) the result is also an int. If the result < 1, it will be truncated to 0.
You can fix it by casting to double before the division : ((double)boyBoy / counter).

A: Apart from the integer division already mentioned in the other answers, your scanning loop is wrong. Your single tokens seem to be separated by a space and there are no line breaks, but you're reading full lines with inFile.hasNextLine() and inFile.nextLine(). So inFile.nextLine() will return the entire file content!
Instead, use inFile.hasNext() and inFile.next() to read single tokens only:
while (inFile.hasNext()) {
    counter++;
    String token = inFile.next( );
    if (token.equals("BB")) boyBoy++;
    else if (token.equals("BG") || token.equals("GB")) boyGirl++;
    else girlGirl++;
}


text:
Q: How to sort an array by amount of unique groups it can create I have no idea how to formulate the question correctly, but what I want is the following:
Let's say there's an array like
[1,1,1,1,2,2,2,3,3,3,4,4,5]

How can I sort it, until this becomes the output:
[1,2,3,4,5,1,2,3,4,1,2,3,1]

To make the output a bit more readable:
[[1,2,3,4,5],[1,2,3,4],[1,2,3],[1]]

What I've come up so far is:
array = [1,1,1,1,2,2,2,3,3,3,4,4,5]
array.group_by{|n| n }.values.transpose.flatten

But this throws an error due to not having the same amount of numbers.
Can anybody help?

A: it took a while to do this but here is what you want:
array = [1,1,1,1,2,2,2,3,3,3,4,4,5]

a = array.group_by{|n| n }.values.sort_by(&:length).reverse

a.each{|q| (a[0].size-q.size).times{q<<nil}}

a.sort.transpose.flatten.compact

it produces:
  => [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1]

*you have 3 number of twos

A: ▶ array = [1,1,1,1,2,2,2,3,3,3,4,4,5]
▶ tap = array.group_by(&:to_i).values.sort do |i, j|
▷   result = j.length <=> i.length
▷   result.zero? ? i <=> j : result
▷ end
▶ tap.map do |e|
▷   e.fill nil, (e.length...tap.first.length)
▷ end.transpose.flatten.compact
#⇒ [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1]

A: Came up with my own answer as well.
array = [1,1,1,1,2,2,2,3,3,3,4,4,5]

# group all the values in single array
a = array.group_by{|n| n }.values.sort{|a,b| b.size <=> a.size }

# fill every other space in the other subarrays with nil
a.each{|q| q.fill(nil, (a[0].size...q.size)) }

# transpose, flatten and remove all the nil values
a.transpose.flatten.compact

If anyone knows a 'smaller' more readable answer, please tell.

A: Let arr be your array. Then:
def transform(arr)
  a = arr.sort
  b = []
  until a.empty?
    u = a.uniq
    b << u
    a = a.difference(u)
  end
  b
end

The helper Array#difference is defined in my answer here.
Let's try it:
transform(arr)
  #=> [[1,2,3,4,5], [1,2,3,4], [1,2,3], [1]]


text:
Q: Picard group of Schubert varieties Let $G$ be a semisimple linear algebraic group, $P$ be a parabolic subgroup and $w$ be an element of the Weyl group of $G$. I want to calculate the Picard group of the Schubert variety $X_P(w):=\overline{BwP/P} \subset G/P$. I'm particularly interested in the case of a maximal parabolic subgroup, but I suppose the general case is not much harder. In that case, I read without proof, that $\text{Pic}(X_P(w)) \cong \mathbb{Z}$ (of course if $w$ is non trivial). I would also hope, that there is a very ample generator in that case?
I have no problems to calculate the divisor class group, which is freely generated by the divisorial Schubert subvarieties. So the problem lies mainly in the non-smooth case.
A good reference on this topic would also be nice.

A: Alex Yong and I work this out in our paper for the case of the Borel subgroup, but I'm pretty sure it's the same for every parabolic.
When is a Schubert variety Gorenstein?, Advances in Math. 207 (2006), 205-220.
Please note our conventions in that paper are backwards from yours in that our Schubert varieties are $\overline{B_-wB/B}$.
We don't say explicitly what happens for groups other than GL_n, but you can do the same thing using the appropriate Monk-Chevalley formula for the group in question.
EDIT: More details upon glancing at my own paper... Mathieu (reference in comments) shows that every line bundle on a Schubert variety is the restriction of a line bundle on the homogeneous space.  (Actually, iirc the proof in the finite dimensional case predates Mathieu.)  This means the Picard group of the Schubert variety will be the same as that of the homogeneous space unless some nontrivial line bundle restricts to a trivial one.  For $G/P$ where $P$ is a maximal parabolic, this only happens if your Schubert variety is a point.
What we do is actually work out the Picard group as a subgroup of the class group.


text:
Q: EditText width parameter fill_parent does not fill width of parent container? In my xml layout file all of EditText Views do not fill the width of the parent container? They are contained within a relative layout file and I use a fragment to inflate the view.
For some strange reason Eclipse shows the layout file with the correct view but the emulator does not.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dip" >

    <TextView
        android:id="@+id/NameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dip"
        android:layout_marginTop="47dip"
        android:text="Name" />

    <EditText
        android:id="@+id/NameEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/NameTextView"
        android:layout_toRightOf="@+id/NameTextView"
        android:layout_alignRight="@+id/GenderSpinner"

        android:ems="10" />

    <TextView
        android:id="@+id/GenderTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/NameTextView"
        android:layout_below="@+id/NameTextView"
        android:layout_marginTop="26dip"
        android:text="Gender" />

    <Spinner
        android:id="@+id/GenderSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/NameEditText"
        android:layout_toRightOf="@+id/GenderTextView"
        android:layout_alignBottom="@+id/GenderTextView" />

    <TextView
        android:id="@+id/HeighttextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/GenderTextView"
        android:layout_below="@+id/GenderTextView"
        android:layout_marginTop="35dip"
        android:text="Height" />

    <EditText
        android:id="@+id/HeighteditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/HeighttextView"
        android:layout_toRightOf="@+id/HeighttextView"
        android:layout_alignRight="@+id/GenderSpinner"
        android:ems="10"
        android:hint="eg:5'11">

    </EditText>

      <TextView
        android:id="@+id/WeightTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/HeighttextView"

        android:layout_below="@+id/HeighttextView"
        android:layout_marginTop="19dp"
        android:text="Weight" />

    <EditText
        android:id="@+id/WeighteditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/WeightTextView"
        android:layout_alignRight="@+id/GenderSpinner"
        android:layout_toRightOf="@+id/WeightTextView"
        android:ems="10"
        android:hint="lbs." >

    </EditText>

     <TextView
        android:id="@+id/LoginIdTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/WeightTextView"
        android:layout_below="@+id/WeightTextView"
        android:layout_marginTop="19dip"
        android:text="Login Id" />

    <EditText
        android:id="@+id/LoginditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/LoginIdTextView"
        android:layout_alignRight="@+id/GenderSpinner"
        android:layout_toRightOf="@+id/LoginIdTextView"
        android:ems="10"
         >

    </EditText>

     <TextView
        android:id="@+id/PasswordTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/LoginIdTextView"
        android:layout_below="@+id/LoginIdTextView"
        android:layout_marginTop="19dip"
        android:text="Password" />

    <EditText
        android:id="@+id/PasswordEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/PasswordTextView"
        android:layout_alignRight="@+id/GenderSpinner"
        android:layout_toRightOf="@+id/PasswordTextView"
        android:ems="10"
         >

    </EditText>

</RelativeLayout>


text:
Q: find exact word as part of a string I need to write a single SQL statement to list all the tracks that have the exact word 'right' (including both upper and lower cases) as part of the name in a table called Track. In other words, it will NOT include track names with words like 'rights' or 'righteous' in the output
I wrote this but I keep getting words with letters before or after right eg: brighter or rights.
SELECT name

FROM Track

WHERE name LIKE "%right%";

A: LIKE is for pattern matching. % means "zero or more characters of anything" like a * wildcard in other systems. name LIKE "%right%" says "name is the word 'right' with anything before and after it". That's why you're getting "brighter" and "rights".
With a regular expression you could write something like /\bright\b/ where \b means "word break". But SQLite requires a plugin to use regexes and LIKE has no equivalent. All you have to work with is % (zero or more characters) or _ (any one character). Best you can do is match spaces such as LIKE "% right %" but that only works if there are spaces around "right". "right now" won't match.
If you want to pick the word "right" out of values like "right left" and "turn right" and "left right left" you need to cover four possibilities.

*

*It's at the start.

*It's at the end.

*It's in the middle.

*It's alone.

This means four expressions.
name LIKE "right %"   or
name LIKE "% right"   or
name LIKE "% right %" or
lower(name) = "right"

LIKE in SQLite is case-insensitive by default. = is not, so lower(name) is necessary to normalize the value to lower case.


text:
Q: How do I remove this error which comes after using import keras I am new to Tensorflow and Keras and stuff and I'm getting this error now when I try importing Keras.
Surprisingly, Keras was working fine until last night.
I had issues with installing OpenCV and somehow I successfully installed that library. But then I started getting errors for CUDA drivers and cuDNN.
I somehow fixed those errors too by downloading cuda_11.0.3_win10_network and cudnn-9.0-windows10-x64-v7.1. Now I am stuck with these TensorFlow errors and I do not know what to do.
Please Help.
Thanks!!
ImportError                               Traceback (most recent call last)
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     57
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59   from tensorflow.python.pywrap_tensorflow_internal import __version__

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in <module>
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

~\Anaconda3\lib\imp.py in load_module(name, file, filename, details)
    241         else:
--> 242             return load_dynamic(name, filename, file)
    243     elif type_ == PKG_DIRECTORY:

~\Anaconda3\lib\imp.py in load_dynamic(name, path, file)
    341             name=name, loader=loader, origin=path)
--> 342         return _load(spec)
    343

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-2-88d96843a926> in <module>
----> 1 import keras

~\Anaconda3\lib\site-packages\keras\__init__.py in <module>
      1 from __future__ import absolute_import
      2
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\Anaconda3\lib\site-packages\keras\utils\__init__.py in <module>
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 from . import losses_utils
      8 from . import metrics_utils

~\Anaconda3\lib\site-packages\keras\utils\conv_utils.py in <module>
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10
     11

~\Anaconda3\lib\site-packages\keras\backend\__init__.py in <module>
----> 1 from .load_backend import epsilon
      2 from .load_backend import set_epsilon
      3 from .load_backend import floatx
      4 from .load_backend import set_floatx
      5 from .load_backend import cast_to_floatx

~\Anaconda3\lib\site-packages\keras\backend\load_backend.py in <module>
     88 elif _BACKEND == 'tensorflow':
     89     sys.stderr.write('Using TensorFlow backend.\n')
---> 90     from .tensorflow_backend import *
     91 else:
     92     # Try and load external backend.

~\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py in <module>
      3 from __future__ import print_function
      4
----> 5 import tensorflow as tf
      6 from tensorflow.python.eager import context
      7 from tensorflow.python.framework import device as tfdev

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\__init__.py in <module>
     26
     27 # pylint: disable=g-bad-import-order
---> 28 from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
     29 from tensorflow.python.tools import module_util as _module_util
     30

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\__init__.py in <module>
     47 import numpy as np
     48
---> 49 from tensorflow.python import pywrap_tensorflow
     50
     51 # Protocol buffers

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     72 for some common reasons and solutions.  Include the entire stack trace
     73 above this error message when asking for help.""" % traceback.format_exc()
---> 74   raise ImportError(msg)
     75
     76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "C:\Users\Harsh\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Harsh\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Harsh\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Harsh\Anaconda3\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Harsh\Anaconda3\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


text:
Q: How to do convert the following ino lambda expression(method syntax)? int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
    from a in numbersA
    from b in numbersB
    where a < b
    select new { a, b };

A: You could try something like this:
var pairs = numbersA.SelectMany(a => numbersB.Where(b => b>a)
                    .Select(b => new { a, b }));

Please see this .NET Fiddle
What does SelectMany ?

Projects each element of a sequence to an IEnumerable and flattens
  the resulting sequences into one sequence.

So from the result of the SelectMany that would contain all the combinations between the current a and all the numbers in the numbersB array, which are greater than a, we select an anonymous type with two properties, a and b. Doing this for all the numbers in numbersA we get that we want.


text:
Q: Does filtering of data take place in the controller, service or repository layers? I am using ASP.NET MVC 3.  I get my view's data in the following sequence:
Controller -> Service Layer -> Repository

In my repository I have a GetAll method that brings back all the records for a specific object, like Category.
So if I need a list of the all the categories then in my controller I would have something like:
IEnumerable<Category> categories = categoryService.GetAll();

In the service layer I would have something like:
public IEnumerable<Category> GetAll()
{
     return categoryRepository.GetAll();
}

Now this is what I need to know where do I actually start to filter the data?  Can it be done anywhere in one of these 3 layers or does it only have to be in the repository layer?  Lets say I need all the parent categories.  Do I have the .GetAll.Where(x => x.ParentCategoryId == null); in my controller, service layer, or repository layer?
Do I have it like this in my controller:
IEnumerable<Category> categories = categoryService.GetParentCategories();

And in my service layer I can have:
public IEnumerable<Category> GetParentCategories()
{
     return categoryRepository.GetAll.Where(x => x.ParentCategoryId == null);
}

Or does my service layer have to look like this:
public IEnumerable<Category> GetParentCategories()
{
     return categoryRepository.GetParentCategories();
}

And then in my repository layer like this:
public IEnumerable<Category> GetParentCategories()
{
     return GetAll()
          .Where(x => x.ParentCategoryId == null);
}

Please can someone help clarify this confusion that I have.  There might be different scenarios.  I might bring back all categories that have an active status.  I might bring back categories with an inactive status.  Then do I need a method for each?

A: You should filter at the closest you can from the data source, otherwise you'll be retrieving records to upper layers that will just be discarded due to a filtering option. This does not scale well, so you need to expose filtering capabilities at all layers that require it, but make sure that the actual filtering is performed in lowest layer possible, generally it is performed at the database level.
In the example you posted if use GetAll which return an IEnumerable of all the records and only then apply the filtering you'll have problems in the future because you're basically loading an entire table into memory and only then applying a filtering.
Since you're using EF you could take advantage of the deferred execution properties of the IQueryable. Check:
.NET Entity Framework - IEnumerable VS. IQueryable
Should a Repository return IEnumerable , IQueryable or List?

Update: Following up on your comment you should also check:
LINQ to entities vs LINQ to objects - Are they the same?

A: You should always try to fetch as little as possible from the database. And you should therefore do all filtering in your repository classes.
Many articles suggests that you create and use generic repositories.  But imho they will not work very well when your application grows. I recommend that you create proper repository classes with proper search methods like:
emailRepository.GetForUser("Ada");
userRepository.GetNewUsers();

First of all, you hide implementation details like how to identify new users. It also makes the code easier to understand and extend than using a generic query.
You can also add some filtering options:
emailRepository.GetForUser("Ada", Filtering.New().Paged(1, 20).SortedBy("FirstName"));

Unlike @JoãoAngelo I do NOT recommend that you use IQueryable outside of your repository. By doing so you'll move the database execution to outside your repository class. And that means that any errors can no be handled by your repository.


text:
Q: Sheet selection from dropdown I have a sheet "PO", which holds data for google docs template. After a doc from template is generated, all data from that sheet goes into another sheet "Project 01" (a register of all POs for that project).
With the code that I have, I can only do this with one Project sheet with getSheetbyName, but I need to do this for multiple projects, that is, PO data needs to go the appropriate project.
Ideally, I would like to have a dropdown with sheet names, where the data will be copied to the appropriate sheet if the names match in the dropdown. How would I accomplish this?
My code:
var sss = SpreadsheetApp.openById('ahkj54IIndlskdjf123hdUTS');
var ss = sss.getSheetByName('PO');
var range = ss.getRange('A2:I50');
var data = range.getValues();

var tss = SpreadsheetApp.openById('78udjUdklo78354fghUjdlIWS24Chf');
var ts = tss.getSheetByName('Project 01');

ts.getRange(ts.getLastRow()+1, 1,49,9).setValues(data);

A: I created the data validation manually.
function onEdit(e) {
  //e.source.toast('entry');
  const sh = e.range.getSheet();
  const shts = ['Sheet1','Sheet2','Sheet3','Sheet4'];
  const idx = shts.indexOf(e.value)
  if(sh.getName() == 'Sheet0' && e.range.columnStart == 1 && e.range.rowStart > 1 && ~idx) {
    let tsh = SpreadsheetApp.getActive().getSheetByName(shts[idx]);
    sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).copyTo(tsh.getRange(tsh.getLastRow() + 1,1));
  }
}

Sheet0:(aftter two operations):

COL1
COL2
COL3
COL4
COL5
COL6
COL7
COL8
COL9
COL10

Sheet1
1,2
1,3
1,4
1,5
1,6
1,7
1,8
1,9
1,10

Sheet4
2,2
2,3
2,4
2,5
2,6
2,7
2,8
2,9
2,10

3,2
3,3
3,4
3,5
3,6
3,7
3,8
3,9
3,10

4,2
4,3
4,4
4,5
4,6
4,7
4,8
4,9
4,10

Sheet 1:

Sheet1
1,2
1,3
1,4
1,5
1,6
1,7
1,8
1,9
1,10

Sheet4:

Sheet4
2,2
2,3
2,4
2,5
2,6
2,7
2,8
2,9
2,10


text:
Q: Converting string to time in PHP in this example I have a string for a date and a string for a time. I need to convert them to the format Y-m-d h:i
This is what I have so far. I am converting the date string to date format:
$fechasolucion = $_POST['fecha'];
$date = date("Y-m-d",strtotime($fechasolucion));

Now I need to include the string $hora (19:29) to the time part of the given date.
I need to get at the end this output:
$fecha = "2017-07-01"
$hora = "19:29"

$date = "2017-07-01 19:29"

A: You can concatinate the two variables $fecha and $hora and then convert it to time.
<?php
    $fecha = "2017-07-01";
    $hora = "19:29";

    $date_string = $fecha . ' ' . $hora;
    $time = strtotime( $date_string );

    echo date( 'Y-m-d H:i', $time );
?>

Output:
2017-07-01 19:29


text:
Q: Method of approach for Equivalence relations Let R be the binary relation on N×P(N) defined by (u, V )R(w, X) if and only if u×|V | $\leq$ w×|X|.
Is R reflexive? Is R symmetric? Is R antisymmetric? Is R transitive? Is R a partial order?
I understand from this question that R is a powerset of natural numbers multipled by another set of natural numbers. But what i dont understand is how can it possibly be any of these, like you cant have a nat number set where 1 is equivalent to 2 and 2 is equivalent to 3,
or am i misunderstanding the question as a whole? I need help understanding the questions mainly.

A: The set (call it) $A$ on which the relation has been defined is the cartesian product of two sets $\Bbb{N}$ and the power set of natural numbers $\mathcal{P}(\Bbb{N})$.
$$A=\Bbb{N} \times \mathcal{P}(\Bbb{N})=\{(n,A)\, | \, n \in \Bbb{N} \text{ and } A \in \mathcal{P}(\Bbb{N})\}.$$
So examples of objects inside the set $A$ are the pairs
 $$\left(7, \{1,3,5,7,11,13\}\right), \quad (1, \emptyset), \quad (23, \{2^k \, | \, k \geq 0\})$$ where the first component is a natural number and the second component is a subset of $\Bbb{N}$.
Two elements $(n,A)$ and $(m,B)$ are related if $n\cdot |A| \leq m \cdot |B|$, where $|S|$ is the cardinality of set $S$.
For example, $(1, \emptyset)$ is related to  $\left(7, \{1,3,5,7,11,13\}\right)$ because $0=1 \cdot 0 \leq 7 \cdot 6=42$.
Now we can explore the question in general.
Is the relation reflexive?
For that we need to determine if $(n,A)$ be related to itself for all $n \in \Bbb{N}$ and for all $A \in \mathcal{P}(\Bbb{N})$, i.e. can we guarantee that $$n \cdot |A| \leq n \cdot |A|\,?$$
Assuming that $0 \not\in \Bbb{N}$, this will be true for both finite and infinite subsets of $\Bbb{N}$. Hence reflexive.
Is the relation symmetric?
We ask if $(n, A)$ is related to $(m,B)$, should $(m,B)$ be related to $(n,A)$?
In the example I mentioned above, ask yourself, will $$\left(7, \{1,3,5,7,11,13\}\right) \text{ be related to } (1, \emptyset) \,?$$
Hopefully you can pick up from here.


text:
Q: How can jenkins use maven deploy url? I use Jenkins to build  and deploy my java application with maven deploy.
when maven deploy zip/war to nexus then  use "Publisher over ssh" to call a command on remote server.
How can i get the deploy url and pass to the command? like ./command.sh $Deploy_Url


text:
Q: Error in installing JEDI - please install the dependencies first I downloaded JEDIVCL package.... according to its help i have to run install.bat from jcl folder and then run install.bat from jvcl folder. i launched install.bat from jvcl folder but i received this error:

and if run install.bat from jcl folder receive this error:

How can I solve this problem? if its possible give me steps to install this package.

A: Second error message is crash of Delphi compiler.
install.bat asks Delphi to compile JCL installer, but... Delphi compiler crashes.
This is definitive sign that there is a problem with your Delphi compiler!
Try to install available all updates. Also, try to open installer project in IDE and compile it from IDE (without command-line compiler).

A: Sounds like you have problem with your Delphi installation.  If you have just installed Delphi make sure you have run it at least once.
You will need to have the DCC32.EXE command line compiler to install JCL.  If I remember correctly this was not shipped in the Turbo or Trial editions of the product.
The JCL/JVCL look in the registry for the location of your Delphi Installations, some versions of Delphi update the registry on the first launch of the product.


text:
Q: How create pod with unrar under OpenShift? I want to deploy my app, that using unrar, to OpenShift. But by default there is no unrar in /usr/bin directory in my deployment pod.
How to add functionality such as unrar or perl to OpenShift pod?

A: The contents of your deployment pod are dictated by the container image that it is deploying.
You can build your own container image containing any tools you like using the buildah, podman, or docker CLI tools. There are many resources online detailing how this is done.


text:
Q: MySQL/PHP Array to Javascript So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.
Here is my current code:
<?php
    $sql = "SELECT * FROM potentials";
    $result = mysql_query($sql) or die(mysql_error());
    $potential = mysql_fetch_array($result);
    echo json_encode($potential);
?>

And my Javascript:
<script type="text/javascript">
    $(document).ready(function(){
        var myArray = "<?php print(json_encode($potential)); ?>";
        console.log(myArray)
    )};
</script>

I keep getting "Unexpected number" or "unexpected identifier". Whats going on?

A: json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :
<script type="text/javascript">
$(document).ready(function(){
    var myArray = <?php print(json_encode($potential)); ?>;
    console.log(myArray);
});
</script>

(and it's not an array, it's an object, so you might want to rename your variable ;) )

A: You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this
var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');

Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array
$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
    $array[] = $row;
}

A: <script>
    var data = '<?php echo $data; ?>';
    var json = JSON.parse(data);
    console.log(json[0]); //etc
</script>

Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String


text:
Q: Adding sections to UITableView in 'Edit' Mode I'm working on a basic list workout app right now that keeps track of workouts and then the exercises for each workout. I want to extend the current 'editing' mode of a TableViewController to allow for more advanced editing options. Here is what I have so far:

As you can see, I am inserting a section at the top of the table view so that the title of the workout can be edited. The problem I am facing is twofold:

*

*There is no animation when the edit button is tapped anymore.

*When you try to swipe right on one of the exercises (Squat or Bench press) the entire section containing exercises disappears.

I start by triggering one of two different functions on the setEditing function, to either switch to read mode or edit mode based on whether the boolean editing returns true or false.
override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: true)
    tableView.setEditing(editing, animated: true)
    if editing {
        switchToEditMode()
    } else {
        switchToReadMode()
    }
}

Then I either insert the "addTitle" section (the text field seen in the second image) to an array called tableSectionsKey which I use to determine how to display the table (seen further below), and then reload the table data.
func switchToEditMode(){
    tableSectionsKey.insert("addTitle", at:0)
    self.tableView.reloadData()
}

func switchToReadMode(){
    tableSectionsKey.remove(at: 0)
    self.tableView.reloadData()
}

Here is my tableView data method. Basically the gist of it is that I have the array called tableSectionsKey I mentioned above, and I add strings that relate to sections based on what mode I'm in and what information should be displayed. Initially it just has "addExercise", which related to the "Add exercise to routine" cell
class WorkoutRoutineTableViewController: UITableViewController, UITextFieldDelegate, UINavigationControllerDelegate {
    var tableSectionsKey = ["addExercise"]
}

Then in viewDidLoad I add the "exercise" section (for list of exercises) if the current workout routine has any, and I add the addTitle section if it's in new mode, which is used to determine if the view controller is being accessed from an add new workout button or a from a list of preexisting workouts (so to determine if the page is being used to create a workout or update an existing one)
override func viewDidLoad() {
    super.viewDidLoad()
    if workoutRoutine.exercises.count > 0 {
        tableSectionsKey.insert("exercise", at:0)
    }
    if mode == "new" {
        tableSectionsKey.insert("addTitle", at: 0)
    }
}

Then in the cellForRowAt function I determine how to style the cell based on how the section of the table relates with an index in the tableSectionsKey array
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let section = indexPath.section
    let sectionKey = tableSectionsKey[section]
    let cellIdentifier = sectionKey + "TableViewCell"

    switch sectionKey {
    case "addTitle":

        guard let addTitleCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AddTitleTableViewCell else {
            fatalError("Was expecting cell of type AddTitleTableViewCell.")
        }
        setUpAddTitleTableViewCell(for: addTitleCell)

        return addTitleCell

    case "exercise":

        guard let exerciseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ExerciseTableViewCell else {
            fatalError("Was expecting cell of type ExerciseTableViewCell.")
        }
        let exercise = workoutRoutine.exercises[indexPath.row]
        setUpExerciseTableViewCell(for: exerciseCell, with: exercise)

        return exerciseCell

    case "addExercise":

        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)

        return cell

    default:
        fatalError("Couldn't find section: \(section), in WorkoutRoutineTableView" )
    }
}

private func setUpExerciseTableViewCell(for cell: ExerciseTableViewCell, with exercise: Exercise) {
    let titleText = exercise.name
    let detailsText = "\(exercise.sets)x\(exercise.reps) - \(exercise.weight)lbs"
    cell.titleLabel.text = titleText
    cell.detailsLabel.text = detailsText
}

private func setUpAddTitleTableViewCell(for cell: AddTitleTableViewCell) {
    cell.titleTextField.delegate = self
    if (workoutRoutine.title != nil) {
        cell.titleTextField.text = workoutRoutine.title
    }
    // Set the WorkoutRoutineTableViewController property 'titleTextField' to the 'titleTextField' found in the addTitleTableViewCell
    self.titleTextField = cell.titleTextField
}

This isn't all of my code but I believe it is all of the code that could be relevant to this problem.

A: Your animation issue is due to the use of reloadData. You need to replace the uses of reloadData with calls to insert or delete just the one section.
func switchToEditMode(){
    tableSectionsKey.insert("addTitle", at:0)
    let section = IndexSet(integer: 0)
    self.tableView.insertSections(section, with: .left) // use whatever animation you want
}

func switchToReadMode(){
    tableSectionsKey.remove(at: 0)
    let section = IndexSet(integer: 0)
    self.tableView.deleteSections(section, with: .left) // use whatever animation you want
}


text:
Q: UIImage Gaussian Blur with vImage I am trying to find a faster way to generate Gaussian Blur image, this blog works great with most of the image.
But when image has transparent backgroudcolor, the blured image looks bad
The code below is copied from the blog:
-(UIImage *)vImageBlurWithNumber:(CGFloat)blur
{
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 100);
    boxSize = boxSize - (boxSize % 2) + 1;

    CGImageRef img = self.CGImage;

    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;

    void *pixelBuffer;

    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);

    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);

    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);

    pixelBuffer = malloc(CGImageGetBytesPerRow(img) *
                     CGImageGetHeight(img));

    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");

    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);

    // may be i should modify last 2 parameter below ,how ?
    error = vImageBoxConvolve_ARGB8888(&inBuffer,
                                   &outBuffer,
                                   NULL,
                                   0,
                                   0,
                                   boxSize,
                                   boxSize,
                                   NULL,
                                   kvImageEdgeExtend); //        kvImageBackgroundColorFill ?

    if (error) {
        NSLog(@"error from convolution %ld", error);
    }

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(
                                         outBuffer.data,
                                         outBuffer.width,
                                         outBuffer.height,
                                         8,
                                         outBuffer.rowBytes,
                                         colorSpace,
                                         kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];

    //clean up
//    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);

    free(pixelBuffer);
    CFRelease(inBitmapData);

    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);

    return returnImage;
}

I have tried another way to make Gaussian Blur Effect ,
by using Apple WWDC 2013 UIImage-ImageEffects category,
but the effect of this category is more like Frosted glass instead of Gaussian Blur.
Blur in Core Image works fine, but it is so slow than the vImage way.
GPUImage also slower than vImage way.
Please help me to modified the vImage code above,
i have tried a lot ,and post the code with demo here;
:)

A: It would be useful to see what looks bad about it.
If it is just regions near the transparent areas, you might try to premultiply the image first. That will keep the meaningless colors in the fully transparent areas from bleeding into the rest of the image.

A: You could also do something like:
var noAlpha = CIVector(x: 0, y: 0, z: 0, w: 1)

image.imageByApplyingFilter("CIColorMatrix",
    withInputParameters: ["inputAVector": noAlpha])

to get rid of the alpha. If you need to chain with other CIFilters this would be more efficient.


text:
Q: Is it safe to change text datatype to nvarchar(max) in SQL Server I have an old SQL Server database that till uses the text datatype. I would like to change this to nvarchar(max) to allow for emojis and other modern stuff.
Is it safe to just change the database? Or is it safer to create a new nvarchar(max) column and update all rows to copy data from the old column to the new?

A: Just change the database using ALTER TABLE ... ALTER COLUMN
Just in case anyone mentions it, there were some old edge cases where data was lost or changed, but these have been patched (MS KB 968914 for example)


text:
Q: Multiplexer CD74HC4051, always giving a true out I'm testing a multiplexer from Texas Instruments (CD74HC4051). Both +5V and Ground rails are connected to the Arduino Duemilanove board.
I've got a +5V signal in the channel A7 (pin4) and A0 (pin 13), moving my address selectors to different addresses than A0 and A7 still keeps the output active.
When dashing through all the 8 addresses, the output is basically always +5V.
How come?
The images below are: the CD74HC4051 pinout, my setup connections, and the 4051 truth table. The photos at the end of the post show three different address configurations.
CD74HC4051 Pinout:

Setup connections:

Photo 1 - Address False, False, False:

Photo 2 - Address True, False, False:

Photo 3 - Address True, True, True:

Below is the schematics with the pull down resistors. This solves the impedance issue of the IC pin internal resistance and possible noise and float signal to the pin.

A: Being CMOS, you need to make sure that all of the address inputs are either connected to Vcc or GND since once you charge up the gate capacitances of the decoder's input MOSFETs they'll stay charged up for a long time when the address dip switches go open-circuit.
I don't see any pull-downs on the chip side of your address dip switch, so you need to connect about 10k from each of them to GND.


text:
Q: How To Increase SessionTimeOut I did by writing this line into web.config
<sessionState timeout="540"/>
but My client's Session Expire within 20-40 minute
is there any other way to Increase SessionTimeout for 8-9 hours ?
thanks

A: Perhaps you could toss something in you global.asax.cs file, to reset the expire.  I'd put it in the Application_PreRequestHandlerExecute method / event.
  var cookie = Request.Cookies["ASP.NET_SessionId"];
  cookie.Expires = DateTime.Now.AddHours(8);
  Response.Cookies.Set(cookie);

A: It's likely that your IIS application pool is recycling. By default it will shut down the worker process after being idle for a certain amount of time.
You could use SQL Server backed session state, or you could increase the worker process idle timeout limit.


text:
Q: Finding the cause for deadlock in multi threading? A multi threaded application freezes. Perhaps it was caused by a deadlock. If yes, then how do we find the cause for the deadlock ? Any tools and strategies for doing this systematically ?

A: *

*When possible, use a lock-free data structure like a ConcurrentLinkedQueue.  By definition, a lock-free data structure cannot cause a deadlock.

*Always acquire locks in the same order.  If your resources are A, B, and C, then all threads should acquire them in the order of A -> B -> C, or A -> C, or B -> C, etc.  Deadlock can occur if one thread acquires them in the order A -> B -> C while another thread acquires them in the order C -> B -> A.

*Use lock timeouts - if a timer expires then a thread releases its locks.  Be sure to log when this occurs so that you can re-examine your lock ordering.

*Use deadlock detection.

A:
How do we find the cause for the deadlock ?

*

*Using Program
java.lang.management.ThreadMXBean is the answer to find out deadlock threads in Java.
Here is the short code demo:
import java.lang.management.*;
class  DeadLockDetect
{
    public void findDeadLocks()
    {
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        long[] ids = tmx.findDeadlockedThreads();
        if (ids != null )
        {
            ThreadInfo[] infos = tmx.getThreadInfo(ids,true,true);
            System.out.println("Following Threads are deadlocked");
            for (ThreadInfo info : infos)
            {
                System.out.println(info);
            }
        }
    }
}

*

*Using Tool
JConsole is one of the tools that tells almost all information about the threads running in your code.

A: The first thing I would do is to fetch the thread stack with jstack, which comes with the JDK.
Usage : jstack <pid>
Here you can see the current state of all threads running. You can see threads waitung for locks etc.
Doc : http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstack.html
Here you can see what different threads states exist : http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html


text:
Q: Advantage of importing libraries inside function? So I'm writing a small program in Python. It's not going to be very demanding and is for fun so doesn't necessarily need to be optimized for speed or resources or any of that and I'm far from pro so if this is a ridiculous question sorry, BUT I am curious:
I am defining several small functions (like 5 lines) that will need libraries to be imported (urllib, xml.etree, etc.). Is there a reason to do them outside of the function, like at the beginning of my code, instead of as the first lines of the function? I would think that having it in the function would make it easier to steal those functions effectively in the future but I was also thinking it my slow down things a bit. Is there any hard and fast rule or rule of thumb here? And if not, does anyone have any opinions?

A: Actually, importing the modules locally inside a function would improve efficiency (slightly). Looking up local names is always faster than looking up globals because the global namespace is one of the last that Python checks when searching for a name.
That said, I wouldn't recommend doing this for three reasons:

*

*It wastes lines of code.  Every function which needs a particular module will have to import it.  This means that you will have a lot of repeated import statements.

*It makes the dependencies of your code hard to find.  One of the main reasons that you import at the top of a file is so that the imports are easily visible.

*It goes against PEP 0008, which specifically says:

Imports are always put at the top of the file, just after any module
  comments and docstrings, and before module globals and constants.


text:
Q: Wordpress/JavaScript troubles I'm working on a Wordpress site and I want to use a sliding gallery that I wrote. I've been trying to enqueue it and I'm not having any luck getting it to work. When I look at the developer tools to see what sources are being pulled/if the console is throwing any errors, I'm not even seeing the JavaScript file show up.
file structure as shown on google dev tools for front-page.php (where the slider will exist)

file structure as shown on google dev tools for all other pages

functions.php code:
function glv_scripts() {
    wp_enqueue_style( 'glv-style', get_stylesheet_uri(), array(), _S_VERSION );
    wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array(), null, true );
}
add_action( 'wp_enqueue_scripts', 'glv_scripts' );

A: I finally realized I was missing the footer call in front-page.php, so it wasn't showing up because I had it set to true for the footer but forgot the footer. :S


text:
Q: my state get filled and get empty again ? React-Redux Hello I am having a little problem here, I am trying to render data in my component, here is my component :
// Store data in the global state
const mapStateToProps = ({ moduleState }) => ({
    operationsContrat: moduleState.contrat.operationsContrat
});

// execute the action
const mapDispatchToProps = dispatch => {
    return {
        getOperationContrat: (...args) =>
          dispatch(getOperationContrat(...args))
    };
};

class Operations extends Component {

state = {
    data: []
};

// Nod used
componentDidMount() {
    if (this.props.operationsContrat.data.length === 0) {
        this.props.getOperationContrat(4000003);
    }
}

componentWillReceiveProps(nextProps) {
    if (this.props.operationsContrat.loading && !nextProps.operationsContrat.loading) {
        this.setState({ data: nextProps.operationsContrat.data });
    }
}
render() {
    console.log("operations");
    console.log(this.state.data);
    return (
        <Fragment />
    );
}
}

So I get the data and then my state.data is empty again, whch caused me a problem, because No data is displayed, here is what I see in my console :

So what happens is that my componentWillReceiveComponent is not executed when my render method is executed the last time, I know what happened I guess but I dont know how to solve the problem..
I can provide any needed code if you need it to understand more the problem.
Any help would be much appreciated.


text:
Q: $\operatorname{cov}\left(\int_0^tf(s,T_1)\,dW(s,T_1),\int_0^tf(s,T_2)\,dW(s,T_1)\right)=\text{?}$ Define a random field $W$ so that:

*

*$W(t,T)$ is a standard Brownian motion for every $T$.

*$dW(t,T_1) \, dW(t,T_2)=c(t,T_1,T_2)\,dt$

*$W(t,\cdot)$ is a a continuous function for every $t$.

Suppose $f$ is a deterministic function. I want to find the covariance $$ \operatorname{cov}\left(\int_0^t f(s,T_1) \, dW(s,T_1), \int_0^tf(s,T_2) \, dW(s,T_1)\right). $$
When $W$ is a BM instead of a random field, we can use $XY=\frac{1}{4}[(X+Y)^2-(X-Y)^2]$ to find the covariance but I don't think it is possible in this case. However, my guess is that
\begin{align}
& \operatorname{cov}\left(\int_0^tf(s,T_1)\,dW(s,T_1), \int_0^tf(s,T_2) \, dW(s,T_2)\right) \\[8pt]
= {} & \int_0^t f(s,T_1) f(s,T_2) c(s,T_1,T_2)\,ds.
\end{align}
However, I might be wrong but even if I am right I don't know how exactly to prove this.


text:
Q: SOLR Fuzzy searching seems to ignore certain results I am attempting to run a SOLR query using a notion of "fuzzy searching" on some book titles. I am letting the user input keywords in which I will split up and check against the title of the book to return a result set to the user. With words that exceed 4 characters, I was going to add a fuzzy search of "~1" to allow for any misspellings or similar words within the result set.
An example of searching the keywords of "Mouse" and "give" would yield: (I am only providing this snippet here as proof that my index should contain my desired results)
{
  "responseHeader":{
    "status":0,
    "QTime":1,
    "params":{
      "q":"(CatalogTitle:Mouse AND CatalogTitle: give)",
      "fl":"CatalogTitle, score",
      "start":"0",
      "rows":"50",
      "_":"1663261699801"}},
  "response":{"numFound":9,"start":0,"maxScore":13.280009,"numFoundExact":true,"docs":[
      {
        "CatalogTitle":"If You Give A Mouse An Iphone",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give a Mouse a Cookie",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give A Mouse A Cookie",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give A Mouse A Brownie",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give A Mouse A Cookie",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give A Mouse A Cookie",
        "score":13.280009},
      {
        "CatalogTitle":"If You Give A Mouse A Cookie (Big Book)",
        "score":10.967654},
      {
        "CatalogTitle":"If You Give a Mouse A Cookie Shared Reading Pack",
        "score":10.089267},
      {
        "CatalogTitle":"Si Le Das Una Galletita A Un Raton (If You Give A Mouse A Cookie)",
        "score":7.641327}]
  }}

This is exactly what I would expect for these two keywords.
Now I try "Moose" and "give" but put a ~1 on "Moose" to allow a fuzzy search of it, which I would expect "mouse" to be returned as well:
{
  "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"(CatalogTitle:Moose~1 AND CatalogTitle: give)",
      "fl":"CatalogTitle, score",
      "start":"0",
      "rows":"50",
      "_":"1663261699801"}},
  "response":{"numFound":3,"start":0,"maxScore":12.92557,"numFoundExact":true,"docs":[
      {
        "CatalogTitle":"If You Give A Moose A Muffin",
        "score":12.92557},
      {
        "CatalogTitle":"If You Give A Moose A Muffin (Big Book)",
        "score":10.674932},
      {
        "CatalogTitle":"Si Le Das Un Panecillo A Un Alce (If You Give A Moose A Muffin)",
        "score":7.4373817}]
  }}

As you see, it does not return what I would expect.
I attempt to change it to ~2 to see what happens:
{
  "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"(CatalogTitle:Moose~2 AND CatalogTitle: give)",
      "fl":"CatalogTitle, score",
      "start":"0",
      "rows":"50",
      "_":"1663261699801"}},
  "response":{"numFound":4,"start":0,"maxScore":12.4069805,"numFoundExact":true,"docs":[
      {
        "CatalogTitle":"If You Give A Moose A Muffin",
        "score":12.4069805},
      {
        "CatalogTitle":"If You Give A Moose A Muffin (Big Book)",
        "score":10.246639},
      {
        "CatalogTitle":"Si Le Das Un Panecillo A Un Alce (If You Give A Moose A Muffin)",
        "score":7.1389856},
      {
        "CatalogTitle":"The Law Of Rewards: Giving What You Can't Keep To Gain What You Can't Lose",
        "score":5.767641}]
  }}

This baffles me as it brings back a title with "lose" in it, which does match the ~2 for "moose" by removing the m and swapping an "o" for an "l".
What am I doing wrong here? Is there something that I am overlooking? Clearly fuzzy searching is working for me with the 2nd example, but I can't seem to get it to work when just using "~1".


text:
Q: Inline div not wrapping correctly I have a series of inline divs that aren't wrapping correctly. As the browser is resized, the divs should be aligning flush left but sometimes they are flush right. I've read several articles on this but they don't seem to be the same issue. Any help would be much appreciated. My jsfiddle is http://jsfiddle.net/7uuLaLg4/.

Address (Number & Road) *

<input id="User_Address_Address1" name="User.Address.Address1" style="width: 13em;" type="text" value="1 Main St." />

Address 2 (APT, Suite...)

<input id="User_Address_Address2" name="User.Address.Address2" type="text" value="" />

City*

<input id="User_Address_City" name="User.Address.City" type="text" value="Anytown" />

State*

                <select id="User_Address_StateID" name="User.Address.StateID">
                    <option selected="selected" value="3">Kentucky</option>
                </select>

Zip*

<input class="zip-mask" id="User_Address_Zip" maxlength="5" name="User.Address.Zip" style="width: 5em;" type="text" value="12345" />

County*

                <select id="User_Address_CountyID" name="User.Address.CountyID">
                    <option value="0"></option>
                    <option selected="selected" value="125542">Campbell</option>
                </select>

Country*

                <select id="User_Address_CountryID" name="User.Address.CountryID">
                    <option value="0"></option>
                    <option selected="selected" value="1">United States</option>
                </select>

A: Here is fixed example.
http://jsfiddle.net/7uuLaLg4/2/
.box{
    border: 1px solid black;
    text-align: left;
}

.address .item{
    display: inline-block;
    margin: 0 0 10px 0;
}

A: They are not all the same height which is why sometimes they act like they are floating right.
Something like min-height: 60px; should help.
.address .item {
    display: inline-block;
    min-height: 60px;
}

http://jsfiddle.net/bb1ooguo/1/


text:
Q: How to correct fragment not launching issue? i am launching a activity hosting a fragment with a list of items..
When an item is clicked. The layout is tested for threePane or not.
    public void onFeedSelected(Feed feed) {
    if (isThreePane) {
        addItemsFragment(feed);
    }
    else {
        Intent i=new Intent(this, ItemsActivity.class);

        i.putExtra(ItemsActivity.EXTRA_FEED_KEY, feed.getKey());

        startActivity(i);
    }
}

As you can see if it is not three pane then it launches an activity..This works fine on regular phones.
But if it is a tablet screen the activity isnt launched in the fragment.
Here is my AddFeed() method.
public void addItemsFragment(Feed feed) {
    FragmentManager fragMgr=getSupportFragmentManager();
    ItemsFragment items=(ItemsFragment)fragMgr.findFragmentById(R.id.second_pane);
    FragmentTransaction xaction=fragMgr.beginTransaction();

    if (items==null) {
        items=new ItemsFragment(true);
        items.setOnItemListener(this);

        xaction
            .add(R.id.second_pane, items)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .addToBackStack(null)
            .commit();
    }
    else {
        ContentFragment content=
            (ContentFragment)fragMgr.findFragmentById(R.id.third_pane);

        if (content!=null) {
            xaction.remove(content).commit();
            fragMgr.popBackStack();
        }
    }

I dont understand why its not being launched..When i click the item it does nothing on a tablet device.
EDIT:
private boolean isThreePane=false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    FeedsFragment feeds
        =(FeedsFragment)getSupportFragmentManager()
                                                    .findFragmentById(R.id.feeds);

    feeds.setOnFeedListener(this);

    isThreePane=(null!=findViewById(R.id.second_pane));

    if (isThreePane) {
        feeds.enablePersistentSelection();
    }
}

A: I am not familiar with the Fragment API at all so this is total shot in the dark...
isThreePane=(null!=findViewById(R.id.second_pane));

is getting set to true on the tablet, so that means findViewById(R.id.second_pane) is not returning null. Do you have this second_pane view hard coded in your xml? How does the app decide whether or not the second_pane view should be present? Is it based on screen size at all?
Should you be using something like this:
fragMgr.findFragmentById(R.id.second_pane);

Instead of findViewById? Again I know nothing about fragments api, sorry if that is silly question.


text:
Q: Import text with a specific delimiter into r I want to load log events into a data.table, each log is identified by a timestamp and some logs can contains many lines.
I have the following .txt file :
2016-07-19 00:00:01,421 WARNING Exception happened while transfering for command
                                at java.lang.NumberFormatException
                                at java.lang.Integer.parseInt
                                at java.util.concurrent.Task

2016-07-19 00:01:01,525 DEBUG Upload all environments
2016-07-19 00:01:01,720 DEBUG Upload all environments
2016-07-19 00:02:00,520 WARNING Excpetion happened while transfering for command
                                at java.lang.NumberFormatException

I want to get the following data.table :
      log
1 2016-07-19 00:00:01,421 WARNING Exception happened while transfering for command at java.lang.NumberFormatException at java.lang.Integer.parseInt at java.util.concurrent.Task
2 2016-07-19 00:01:01,525 DEBUG Upload all environments
3 2016-07-19 00:01:01,720 DEBUG Upload all environments
4 2016-07-19 00:02:00,520 WARNING Excpetion happened while transfering for command at java.lang.NumberFormatException

I want to upload each log event into a single line. I tried to use the \n separator :
docs <- read.table("log2.txt",header=FALSE,sep="\n",col.names="log",nrows=1000)

A: Use readLines and then combine rows within data.table:
require(data.table)

raw = data.table(s = readLines('log.txt'))
raw = raw[s != '']
raw[, s := stringr::str_trim(s)]
raw[, idx := cumsum(s %like% '^[0-9]{4}')]
raw[, list(s = paste(s, collapse = ' ')), by = idx]

EDIT: changed year regex, thanks for the comment


text:
Q: How to respond to the photoSaved signal in Blackberry Cascades Ok, so I am using Blackberry 10 Cascades (QT, QML, C++), and I am trying to process photos that get taken by the camera.  I have been looking into how to do this on the internet, and figured out some things, but it's not working yet.  Here's what I have done (I have made a point to highlight the most relevant parts of the code with //---------------RELEVANT LINE(S) OF CODE--------------------------------- to begin and
//------------------------------------------------------------------------ to end the relevant sections.
//Camera.h
#ifndef CAMERA_H_
#define CAMERA_H_

#include <QObject>
#include <Page.h>

namespace bb {
    namespace cascades {
        class Container;
        namespace multimedia {
            class Camera;
        }
    }
}

namespace GDLiteBB {

    class Camera : public QObject, public Page_ {
        Q_OBJECT

        //-----------------RELEVANT LINE OF CODE---------------------
        bb::cascades::multimedia::Camera *cameraDevice_;
        //-----------------------------------------------------------

        static Camera *Camera_;

        Camera(
            QString *qmlFileName = new QString(""),
            QString *qmlVarName = new QString(""),
            QObject *parent = 0);

    public:

        static Camera *getInstance(
            QString *qmlFileName = new QString("main.qml"),
            QString *qmlVarName = new QString("camera"),
            QObject *parent = 0);

        virtual ~Camera();

    Camera *show(bb::cascades::Container *container = 0);

    void showCamera();

        //-----------------RELEVANT LINES OF CODE---------------------
        public slots:
        void onPhotoSaved(const QString &fileName, quint64 length);
       //-------------------------------------------------------------
};

} /* namespace GDLiteBB */

#endif /* CAMERA_H_ */

//Camera.cpp
Camera::Camera(
    QString *qmlFileName,
    QString *qmlVarName,
    QObject *parent)
: QObject(parent),
    Page_(qmlFileName, qmlVarName)
{
    INIT_PAGE

    if (Root_) {
        //-----------------RELEVANT LINES OF CODE---------------------
        cameraDevice_ =
            Root_->findChild<bb::cascades::multimedia::Camera *>("camera1");

        connect(cameraDevice_, SIGNAL(photoSaved(const QString&, quint64)), this,
            SLOT(onPhotoSaved(const QString&, quint64)));
       //----------------------------------------------------------------

    } else {
        cameraDevice_ = 0;
    }
}

//-----------------RELEVANT LINES OF CODE---------------------
void Camera::onPhotoSaved(
    const QString &fileName,
    quint64 length)
{
    disconnect(
        cameraDevice_,
        SIGNAL(photoSaved(const QString&, quint64)),
        this,
        SLOT(onPhotoSaved(const QString&, quint64)));

    qDebug() << "onPhotoSaved";
    qDebug() << "filename is " << fileName << ", length is " << length << "test";
}
//-----------------------------------------------------------------

But when I take a picture, the onPhotoSaved slot is not being triggered, for the qDebug is not happening.
I know that the photo is being saved tho, because in the qml, I have:
Label {
    id: cameraDebug
}
Camera {
    ...
    onPhotoSaved: {
        photoBeingTaken = false;
        cameraDebug.text = "saved photo"
    }
}

and the label, cameraDebug, changes to "saved photo", after taking a photo., so I am catching the QML signal for saved photo, but I need to catch the C++ signal for saved photo, because I need the filename of the photo, and that is not working, as I said above.

A: I figured out the problem.  The line:
cameraDevice_ = Root_->findChild<bb::cascades::multimedia::Camera *>("camera1");

was assinging null, because there was no actual "objectName: camera1" in the qml code, there was only "id: camera1", therefore, there was no way to connect cameraDevice_ to the onPhotoSaved slot, since it was null.
It was a silly bug, but I hope this question and answer might benefit others who are looking to figure out how to process a saved photo in blackberry cascades, or just handle signals and slots in general in QT, or how ever else it might help them.


text:
Q: Как растянуть текст по ширине блока? Каким образом можно решить такую задачу?
Есть несколько div в которых лежат 2 текстовые строки "p". Текст в эти строки подставляется динамически пользователем при вводе в input. Шрифт у текста в каждом блоке разный. Размер шрифта в первой строке 25px, в нижней 20.
Как сделать так, чтобы ширина текста была одинаковой, но при этом font-size  второй строки был всегда меньше размера первой?
https://gyazo.com/585a1b62e7338b2f8464c989c18661c2

A:

function setSpText(e) {
  const el = (e instanceof Event) ? e.target : e;
  let value = el.value,
      outP  = document.querySelector(el.dataset.output || '');
  if (outP)
    value = (value.split('')).map(chr => `<span>${chr}</span>`).join('');
  outP.innerHTML = value;
}

document.addEventListener('DOMContentLoaded', () => {
  for (let inp of document.querySelectorAll('.usertext')) {
    inp.addEventListener('input', setSpText);
    setSpText(inp);
  }
});
.test {
  width: 400px; margin: 1em auto;
  border: 1px dashed #ccc;
}

.line {
  display: flex; flex-wrap: nowrap;
  justify-content: space-between;
  margin: 0;
}
.line.first  { font: 25px monospace; }
.line.second { font: 20px sans-serif; }

.line > span { flex: 0 0 auto; }

<input id="inp-first" class="usertext" data-output=".first" maxlength="20" value="Текст первой строки">

<input id="inp-second" class="usertext" data-output=".second" maxlength="30" value="Мелкий текст второй строки">

A: Есть 2 разных способа решения вашей задачи: через SVG и JavaScript.
Через SVG (решение #1):

.wrapper {
  width: 500px;
  background-color: blue;
  height: 125px;
}

svg {
  width: 100%;
  height: 100%
}

text {
  font-family: Helvetica
}

.name {
  font-size: 25px
}

.desc {
  font-size: 20px
}

  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <text class="name" x="10" y="50" textLength="480" lengthAdjust="spacingAndGlyphs">Есть несколько div</text>
    <text class="desc" x="10" y="80" textLength="480" lengthAdjust="spacingAndGlyphs">текст в эти строки подставляется</text>
  </svg>

Через SVG (решение #2):

.wrapper {
  width: 500px;
  background-color: blue;
  height: 125px;
}

svg {
  width: 100%;
  height: 100%
}

text {
  font-family: Helvetica
}

.name {
  font-size: 25px
}

.desc {
  font-size: 20px
}

  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <text class="name" x="10" y="50" textLength="480" lengthAdjust="spacing">Есть несколько div</text>
    <text class="desc" x="10" y="80" textLength="480" lengthAdjust="spacing">текст в эти строки подставляется</text>
  </svg>

Через JavaScript:

$.fn.strech_text = function() {
  var elmt = $(this),
    cont_width = elmt.width(),
    txt = elmt.html(),
    one_line = $('' + txt + ''),
    nb_char = elmt.text().length,
    spacing = cont_width / nb_char,
    txt_width;

  elmt.html(one_line);
  txt_width = one_line.width();

  if (txt_width < cont_width) {
    var char_width = txt_width / nb_char,
      ltr_spacing = spacing - char_width + (spacing - char_width) / nb_char;

    one_line.css({
      'letter-spacing': ltr_spacing
    });
  } else {
    one_line.contents().unwrap();
    elmt.addClass('justify');
  }
};

$(document).ready(function() {
  $('.stretch').each(function() {
    $(this).strech_text();
  });
});
div {
  width: 500px;
  height: 125px;
  vertical-align: middle;
  padding: 50px 10px;
  background-color: blue
}

.stretch_it {
  white-space: nowrap
}

.justify {
  text-align: justify
}

p {
  margin: 7px 0;
  font-family: Helvetica
}

.name {
  font-size: 25px
}

.desc {
  font-size: 20px
}

Есть несколько div

текст в эти строки подставляется


text:
Q: Why the asymmetry in LinearLayout.generateDefaultLayoutParams() output? According to the docs for the LinearLayout class for the method below:
protected LinearLayout.LayoutParams generateDefaultLayoutParams ()

Returns a set of layout parameters with a width of MATCH_PARENT and a
  height of WRAP_CONTENT when the layout's orientation is VERTICAL. When
  the orientation is  HORIZONTAL, the width is set to WRAP_CONTENT and
  the height to WRAP_CONTENT.

I first noticed this when looking at the code and thought it might be a mistake
so I looked at the doc for clarification, but found that that doc agreed with the code but with no explanation. Why is it asymmetric like this?
In other words, I'd expect a horizontal layout's default height to be the same as a vertical layout's default width and vice versa.  Why is that not the case?  Without explanation, it seems random and haphazard.


text:
Q: VueX actions not mapping. Message - [TypeError: Cannot read property 'dispatch' of undefined] In my Vue code when attempting to run an VueX mapped Action I am receiving the below error message:
[TypeError: Cannot read property 'dispatch' of undefined]
I am stuck at this.retrieveProducts();
Please refer the below screenshot for the error observed by me.
Screenshot of the error message
I am using Django, Webpack and Vue-Cli3.
App.vue
<template>

      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/product-list">Products</router-link>

</template>

main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

import { mapState, mapGetters, mapMutations,mapActions } from 'vuex';

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    methods: {
    ...mapMutations([
        'loadProducts',
    ]),
    ...mapActions([
        'retrieveProducts', // **FAILS HERE (Step-2)**
        'saySomething',
    ]),

    testCall: () => {  // Works here
        alert('You are in removeLink');
    },

    },
    computed: {
        ...mapState([
            'products',
            'products_images',
        ]),
        ...mapGetters([
        ]),
    },
    mounted() {
        alert('mounting now');   // Works here
        this.testCall();         // Works here
        this.retrieveProducts(); // **FAILS HERE (Step-1)**
    },
    render: h => h(App),
    }).$mount('#app');

index.js ..\store
import Vuex from 'vuex';
import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

export default new Vuex.Store({
  state: {
        products: [],
        products_images: [],
    },
    mutations: {
        loadProducts: (state, {products, products_images}) => {
            state.products = products;
            state.products_images = products_images;
        },
    },
    actions: {
        retrieveProducts: () => {
            alert("I NEED TO EXECUTE CODE HERE"); // **FAILS HERE (Step-3)**
        },
    },
    getters: {
    }
});

A: You need to install the Vuex plugin with Vue.use(Vuex).

A: The code works fine after adding the missing code:
import Vue from 'vue';
Vue.use(Vuex);

index.js ..\store
import Vue from 'vue';  // added now
import Vuex from 'vuex';
import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

Vue.use(Vuex); // added now
export default new Vuex.Store({
  state: {
        products: [],
        products_images: [],
    },
    mutations: {
        loadProducts: (state, {products, products_images}) => {
            state.products = products;
            state.products_images = products_images;
        },
    },
    actions: {
        retrieveProducts: () => {
            alert("I NEED TO EXECUTE CODE HERE"); // **FAILS HERE (Step-3)**
        },
    },
    getters: {
    }
});


text:
Q: Cannot connect PySide QTableView selectionChanged signal I am designing a program composed of a 3D viewer and a table with Python 3.4 and PySide bindings.
I have created a TableView with this class:
from PySide import QtGui
from PySide.QtCore import Qt

class MyTableView(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyTableView, self).__init__()
        self.parent = parent
        self.title = "Results"
        self.initUI()

    def initUI(self):
        self.grid = QtGui.QGridLayout(self)

        self.table = QtGui.QTableView()
        self.grid.addWidget(self.table, 0, 0)
        # Configure table
        self.table.verticalHeader().setVisible(False)
        self.table.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)
        self.table.setSortingEnabled(True)
        self.table.setAlternatingRowColors(True)
        self.table.setShowGrid(False)
        self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)

and the model with this other class:
class MyModel(QStandardItemModel):

    def __init__(self, path, *args, **kwargs):
        super(MyModel, self).__init__()
        self.path = path
        self.parse()

    def parse(self):
        with open(self.path) as f:
            self.mydata = yaml.load(f)

        self.setColumnCount(len(self.mydata['headers']) + 1)
        self.setHorizontalHeaderLabels(
            ['ID'] + self.mydata['headers'])
        row = 0
        for ind, val in self.mydata['rows'].items():
            col = 0
            self.insertRow(row)
            self.setItem(row, col, QStandardItem(ind))
            for v in val:
                col += 1
                self.setItem(row, col, QStandardItem(str(v)))

            row += 1

which are then tied together in this controller:
from PySide.QtCore import Qt

class MyController(object):

    def __init__(self, model, view):
        self.model = model
        self.tableview = view.table
        self.fill_table()
        self.connect_signals()

    def fill_table(self):
        self.tableview.setModel(self.model)
        self.tableview.sortByColumn(0, Qt.AscendingOrder)

    def connect_signals(self):
        selectionModel = self.tableview.selectionModel()
        selectionModel.selectionChanged.connect(self.selection_changed)

    def selection_changed(self, selected, deselected):
        print("Selection changed.")

Then, the program is executed through this script:
def main():
    app = QtGui.QApplication(sys.argv)
    MyController(MyModel(sys.argv[1]), MyView())
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

(Note that I haven't posted the main window class, but you get the idea)
The table gets rendered OK, but I am not able to connect the selectionChanged signal to the handler (which should udpate the viewer, but for testing purposes it's only a print statement).
What am I doing wrong? Thanks!
[EDIT]
I have discovered that it works if I use a lambda function to call the handler method. Can someone explain why?!
selectionModel.selectionChanged.connect(lambda: self.selection_changed(selectionModel.selectedRows()))

A: I tried to implement what you wrote and it worked - so I can't be 100% sure of why you are having trouble.  But I suspect it is because of what I had to fix to get it to work at all: I had to sort out some problems you have with garbage collection.
In the example code you give, you create a MyController, a MyModel and a MyView.  But they will all then be garbage collected (in CPython) since you don't keep a reference to them.  If you add a  reference to MyController
my_controller = MyController(MyModel(sys.argv[1]), MyView())

you are almost there, but I think the MyTableView might also then be garbage collected since the controller only keeps a reference to the QTableVIew not the MyTableView.
Presumably using the lanbda function changes the references you are preserving - it preserves the controller and the selection model - and that may be why it is working in that case.
Generally it's a good idea to use the Qt parenting mechanism.  If you simply parented all these objects on the main window (or their natural parent widget) that would have prevented most of these problems.


text:
Q: html tag input id changes with server restart? I am using id element of input tag and type is text of html. I am referring id to check wheater element is present in html page or not. My question if web server/app server is restarted or changed does its id changes?
the example tag

A: No. The only way the id will change is if you set up some way for it to do so (random Id on startup).  I don't know why you would want to do that though.


text:
Q: extending a gem's functionality for my local copy I use the webdriver-user-agent to resize an automated browser easily, and it has user agents and window sizes configurable in a YAML file. I want to add to the YAML file, and I'm wondering what the best way to do this is. I may have additions that only I'll want to use, so I'm ruling out a pull request on Github, and I don't want to add it under the gem's lib directory, because then I will lose my work when I upgrade the gem.
What's the best way to add additional code to a gem?

A: Unfortunately, you're talking about adding configuration to the gem, which is less easy than adding code, but still doable.
You're going to monkeypatch whatever it is that the gem uses to load its YAML configuration to instead load the configuration of your choosing. Looking at the source you can see that the YAML is being loaded by #devices and the filename comes from #devices_file. Fortunately for us (though not so much for performance), the loaded YAML isn't cached so just replacing #devices_file will do what you want:
require 'webdriver-user-agent'
module Webdriver
  module UserAgent
    module Devices
      def devices_file
        File.expand_path("../my-devices.yml", __FILE__)
      end
    end
  end
end

This will look for a file called my-devices.yml in the same directory as the file the above code is in (like your spec_helper.rb or whatnot) - adjust appropriately.


text:
Q: Proving a term converges pointwise by the definition How would I show
$$f_n(x) = n^\alpha x^n (1-x)\qquad \text{for} \: x \in [0,1]$$ converges pointwise  to $0$ by the definition?
I showed that it converges for $x=0,1$ trivially, but I'm not sure how I would use the definition for the interior of the domain.

A: Note that $|f_n(x)| \leq n^{\alpha}|x|^n$ for $x \in (0,1)$, then you need to recall that $\lim_{n \to \infty}{\frac{n^{\alpha}}{x^n}} \to 0$ whenever $x > 1$.