text:
Q: Strings and appending in Python In Python a string is immutable. I find the function string.join() could add the value to a string but it seems the following doesn't work.
#coding: utf-8
if __name__ == "__main__":
    str = "A fox has jumped into the river"
    tmp = ""
    for i in str:
        tmp = tmp.join(i)
    print tmp

I expect the output should be "A fox has jumped into the river", but it output the "r"
why?
Is there any similar methods which is something like string.append()?

A: >>> a = "pp"
>>> b = "kk"
>>> a += b
>>> a
'ppkk'

A: You can append simply by using +:
tmp = tmp + i

which can be combined with an in-place addition assignment:
tmp += i

but this is not nearly as efficient as joining the whole sequence with ''.join():
str = "A fox has jumped into the river"
tmp = ''.join(str)

The latter is of course, rather pointless, as we just took all individual characters of str, and rejoined them into a new, otherwise equal, string. But it is far more efficient than calling + in a loop, as .join() only has to create a new string once, while a loop with + creates new strings for each concatenation.
It gets more interesting when you use a delimiter:
>>> ' - '.join(str)
'A -   - f - o - x -   - h - a - s -   - j - u - m - p - e - d -   - i - n - t - o -   - t - h - e -   - r - i - v - e - r'

The thing to note here is that you call .join() on the delimiter string, not on the sequence you are about to join!

A: >>> '-'.join('a')
'a'

str.join doesn't work like that. That's the reason why "r" is the output, since at the end of the for loop you have set tmp = tmp.join('r') whichc will just result in "r".
This is how str.join is usually used:
>>> '-'.join('abc')
'a-b-c'

or
>>> ', '.join(['foo', 'bar', 'spam'])
'foo, bar, spam'

You want simple string concatenation
tmp = ""
for i in str:
    tmp += i

or use a list and ''.join for efficient string concatenation (the former solution is O(N^2) due to the immutable nature of strings)
tmp = []
for i in str:
    tmp.append(i)
tmp = ''.join(tmp)

(''.join joins the list into a string with an empty string as a separator)
One last note: don't use str as a variable name, it's a built-in.

A: This will do what you want i think:
if __name__ == "__main__":
    str = "A fox has jumped into the river"
    tmp = ""
    for i in str:
        tmp += i
    print (tmp)

The reason you code doesn't work is that join joins all the tokens in the list you are providing, seperated by whatever string you "apply" it to. It doesn't actually append to a string.


text:
Q: How do I configure in-app purchase for iTunes? How do I configure iTunes Connect for in-app purchase?
I have added products in iTunes Connect, but in response.product, it always returns an empty value.
- (void)requestProducts {
    NSSet *productIdentifiers = [NSSet setWithObject:@"com.classic.caddycommonground.t1" ];
    //NSLog(@"product identifier %@",_productIdentifiers);
    self.request = [[[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers] autorelease];
    _request.delegate = self;
    [_request start];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {

    NSArray *items = response.products;

    for(SKProduct *item in items)
    {
        NSLog(@"Product title: %@" , item.localizedTitle);
        NSLog(@"Product description: %@" , item.localizedDescription);
        NSLog(@"Product price: %@" , item.price);
        NSLog(@"Product id: %@" , item.productIdentifier);
    }

    /*
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
        NSLog(@"Invalid Product title: %@" , items.localizedTitle);
        NSLog(@"Invalid Product description: %@" , items.localizedDescription);
        NSLog(@"Invalid Product price: %@" , items.price);
        NSLog(@"Invalid product id: %@" , invalidProductId);
    }
    */

    //NSLog(@"Received products results...");
    NSLog(@"response product %@",response.products);
    self.products = response.products;
    self.request = nil;

    [[NSNotificationCenter defaultCenter] postNotificationName:kProductsLoadedNotification object:_products];
}

A: http://troybrant.net/blog/2010/01/in-app-purchases-a-full-walkthrough/
Follow the above tutorial..First check if your code is valid by comparing..If it is Then ..There is a special section when you get Invalid Products Id in return as response..Go through it..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Locking user in specific activity Is it possible to lock a user in an activity, so that it is impossible to navigate away from it without entering a pin or in other ways "unlocking"? If so, how?
Would be very useful for a an app used in a public setting, like a tablet on display.

A: It is possible, but involves lots of trickery. See the commercial app SureLock which probably does what you want.
If you want to try it yourself, start with redefining the home screen in the AndroidManifest.xml, using
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.HOME" />
</intent-filter>

This will ask for the user's permission when called the first time. It gets complicated when you also want to lock down the recent activities and access to the settings menu.
So, the short answer is yes.

A: I am not sure is there something already available on android, but I think you can check authentication through this method onUserInteraction

A: You cannot stop the user from navigating away from your application via the home button (and you cannot stop other activities from opening). However you are notified when these things happen through your onPause() callback, and if the user returns to you, onResume() is called. You can require a pin at the point of resumption.


text:
Q: How to open Saved Photos Album when touch a button? I have a simple IOS application, and there is a feature that user can save the image of current screen, after user take a screenshot, I will inform them "the image was saved, would you like to open the album?" if user select yes, then open the album, now I can launch the Save Photos album with the following code(this is the event handler when user type the yes button)
- (IBAction)gotoPhotoAlbum:(id)sender
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    [imagePicker.view setFrame:CGRectMake(0, 80, 320, 350)];
    [imagePicker setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

The problem is as soon as I click a photo(thumbnail) in the album, it returns to my app, give me no chance to view the photo, what I want is user can view/edit the photo just as if they open albums directly, and when they done the operation, return to my app, is that possible?


text:
Q: Excel vlookup incorporating SQL table I have an Excel spreadsheet which I use to calculate the cost of a product we sell, (happens to be car insurance).  This product is calculated based on various pieces of information; the customers age, postcode, vehicle, occupation, etc etc.
I enter information onto the main tab of my spreadsheet and then perform lots of vlookup formulas to return the relevant figures from other tabs of the spreadsheet.  An example of one of my vlookups is:
=VLOOKUP(G1,RatesInsurerX!A36:B986786,2,FALSE)
So this looks up the value I enter into cell G1 an matches it to the data found on the workbook tab called RatesInsurerX.
As you can see this particular table contains nearly 1 million rows and excel is starting to struggle so I was wondering if there is a way of doing exactly the same thing only performing the lookup against a SQL table rather than the RatesInsurerX workbook?

A: Good news is you can do this without VBA, quite a few steps though as follows:
1 . First add a new sheet, call this something meaningful like PoscodeLookup.
2 . Next go to Data and select Other Sources and Microsoft Query:

3 . Next select (or create) an ODBC data source that can connect you to your database asd select this (you may need to enter user/pass).
4 . The query designer will ask you to select a table, just click close.

5 . Next select the SQL button:

6 . Now enter the SQL query to get the single value you need, using an example postcode eg:
SELECT TOP 1 [Value] FROM [MyTable] WHERE [Postcode] = 'AB12 1AA';

7 . Now hit OK and OK which should return a single value in the window.
8 . Click on Return data in the toolbar:

9 . Now back in Excel hit properties in the prompt:

10 . Now change the post code you entered into a ? in the definition tab:

11 . Hit OK and OK again and it will prompt for a value, enter a valid postcode and hit enter, this should now give you the value you want in cell A1.
12 . Now click in the cell A1 and go to Data > Properties then Connection properties:

13 . Now in the definition tab you have a Parameters button at the bottom, in here you can fill out as below:

Note, the target cell is the cell where you enter the postcode, tick the refresh box if you want this to re-run the query when the post code changes.
That should be it, let me know if it doesn't work.

A: You can. In the VBA of the sheet, create a function like so:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

and in it's body

*

*Check the Target is the cell you want to base your lookup on (G1)

*If it is, get the data from the DB and put it where it needs to go

Cheers -


text:
Q: Cloud watch Log insights query, combining two querires I currently use two different cloud watch log insights queries one to get total request count and the other to get total error count. Below are the queries:
Total count:
fields @timestamp, @message
| filter @message like /reply.*MyAPI/
|parse @message '"reqID":*' as reqID
| stats count_distinct(reqID) as request_count by bin(1h) as hour

** Error count**
fields @timestamp, @message
| filter @message like /reply.*MyAPI.*Exception/
|parse @message '"reqID":*' as reqID
| stats count_distinct(reqID) as request_count by bin(1h) as hour

However I would like to calculate both total request counts and error request count in each bin and calculate error rates for each bin (error count/total request count) if possible with a single query. How would I go about this?


text:
Q: How to apply If Else statements in Pandas Dataframe? I have a Pandas Dataframe and I am trying to add a new column where the value in the new column is dependant on some conditions in the existing Dataframe. The Dataframe I have is as follows:

Date / Time
Open
High
Low
Close
Volume

2020-06-02 16:30:00
1.25566
1.25696
1.25439
1.25634
2720

2020-06-02 17:00:00
1.25638
1.25683
1.25532
1.25614
2800

2020-06-02 17:30:00
1.25615
1.25699
1.25520
1.25565
2827

2020-06-02 18:00:00
1.25565
1.25598
1.25334
1.25341
2993

2020-06-02 18:30:00
1.25341
1.25385
1.25272
1.25287
1899

2020-07-03 07:00:00
1.24651
1.24673
1.24596
1.24603
600

2020-07-03 07:30:00
1.24601
1.24641
1.24568
1.24594
487

2020-07-03 08:00:00
1.24593
1.24618
1.24580
1.24612
455

2020-07-03 08:30:00
1.24612
1.24667
1.24603
1.24666
552

2020-07-03 09:00:00
1.24666
1.24785
1.24623
1.24765
922

I would like to add a new column called 'Signal', which is dependant on the following if and else statements. I have written these into a Function:
def BullEngulf(df):
    if (df['Open'] <= df['Close'].shift(1)) and (df['Close'] > df['Open'].shift(1)) and (df['Close'].shift(1) < df['Open'].shift(1)):
    return 'Open'
    else:
    return '0'

I have then tried to apply the function as follows:
df['Signal'] = df.apply(BullEngulf)
df

When I run the code, the following error message occurs:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-62-f87af322a959> in <module>
      5         return '0'
      6
----> 7 df['Signal'] = df.apply(BullEngulf)
      8 df

~\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   6876             kwds=kwds,
   6877         )
-> 6878         return op.get_result()
   6879
   6880     def applymap(self, func) -> "DataFrame":

~\anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    184             return self.apply_raw()
    185
--> 186         return self.apply_standard()
    187
    188     def apply_empty_result(self):

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    293
    294             try:
--> 295                 result = libreduction.compute_reduction(
    296                     values, self.f, axis=self.axis, dummy=dummy, labels=labels
    297                 )

pandas\_libs\reduction.pyx in pandas._libs.reduction.compute_reduction()

pandas\_libs\reduction.pyx in pandas._libs.reduction.Reducer.get_result()

<ipython-input-62-f87af322a959> in BullEngulf(df)
      1 def BullEngulf(df):
----> 2     if (df['Open'] <= df['Close'].shift(1)) and (df['Close'] > df['Open'].shift(1)) and (df['Close'].shift(1) < df['Open'].shift(1)):
      3         return 'Open'
      4     else:
      5         return '0'

~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872
    873             if not is_scalar(result):

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'Open'

Please could somebody explain what is wrong with the code above?
Thanks

A: Try:
df['Signal'] = np.where((df['Open'] <= df['Close'].shift(1)) &
                        (df['Close'] > df['Open'].shift(1))  &
                        (df['Close'].shift(1) < df['Open'].shift(1)),
                        'Open', '0')


text:
Q: Como criar conector para active diretory? Preciso criar um conector para Active Diretory,
Encontrei esse exemplo na internet...Ouvi falar do migrations... Sabem como funciona?
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

Alguém pode me explicar como funciona? Como devo fazer essa conexão?

A: Não sei de onde você tirou que Migrations está relacionado com o Active Directory. De qualquer forma, estou constantemente atualizando um Helper que fiz para o Active Directory, e que pode ser usada por qualquer aplicação escrita em C#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

public static class ActiveDirectoryHelper
{
    /// <summary>
    /// Converte uma array de bytes do campo thumbnailPhoto do AD para uma foto.
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    static Image ByteToPhoto(byte[] data)
    {
        if (data != null)
        {
            using (MemoryStream s = new MemoryStream(data))
            {
                return Bitmap.FromStream(s);
            }
        }

        return null;
    }

    /// <summary>
    /// Pesquisa o campo thumbnailPhoto do AD.
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    static Image GetUserPicture(string userName)
    {
        using (DirectorySearcher dsSearcher = new DirectorySearcher())
        {
            dsSearcher.Filter = "(&(objectClass=user) (cn=" + userName + "))";
            SearchResult result = dsSearcher.FindOne();

            using (DirectoryEntry user = new DirectoryEntry(result.Path))
            {
                byte[] data = user.Properties["thumbnailPhoto"].Value as byte[];

                if (data != null)
                {
                    using (MemoryStream s = new MemoryStream(data))
                    {
                        return Bitmap.FromStream(s);
                    }
                }

                return null;
            }
        }
    }

    /// <summary>
    /// Traz um usuário do AD com algumas informações.
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    public static ActiveDirectoryUserViewModel GetADUser(String search)
    {
        using (var context = new PrincipalContext(ContextType.Domain, "meudominio.com"))
        {
            var result = UserPrincipal.FindByIdentity(context, search);

            return new ActiveDirectoryUserViewModel
            {
                Sid = result.Sid,
                DisplayName = result.DisplayName,
                Email = result.EmailAddress,
                Mapped = true,
                UserName = result.UserPrincipalName,
                FirstName = result.GivenName,
                MiddleName = result.MiddleName,
                Surname = result.Surname,
                VoiceTelephoneNumber = result.VoiceTelephoneNumber
            };
        }
    }

    /// <summary>
    /// Traz todos os usuários das unidades organizacionais "Usuarios" e "SP".
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<ActiveDirectoryUserViewModel> GetADUsers()
    {
        using (var context = new PrincipalContext(ContextType.Domain, "meudominio.com", "OU=Usuarios,OU=SP,DC=meudominio,DC=com"))
        {
            UserPrincipalExtended userPrincipal = new UserPrincipalExtended(context);
            userPrincipal.Enabled = true;

            using (var searcher = new PrincipalSearcher(userPrincipal))
            {
                foreach (Principal result in searcher.FindAll().Where(r => r.DisplayName != ""))
                {
                    // DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                    UserPrincipalExtended upe = result as UserPrincipalExtended;

                    if ((upe.VoiceTelephoneNumber ?? "").Trim() != "" && (upe.Department ?? "").Trim() != "")
                    {
                        yield return new ActiveDirectoryUserViewModel
                        {
                            Sid = upe.Sid,
                            DisplayName = upe.DisplayName,
                            // UserName = de.Properties["name"].Value.ToString()
                            UserName = upe.UserPrincipalName,
                            Department = upe.Department,
                            VoiceTelephoneNumber = upe.VoiceTelephoneNumber
                        };
                    }
                }
            }
        }
    }

    /// <summary>
    /// Traz um usuário do AD por login.
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static ActiveDirectoryUserViewModel GetADUserByLogin(String name)
    {
        var filter = "(&(objectClass=user)(objectCategory=person)(samaccountname=" + name.Replace("DOMINIO\\", "") + "))";
        using (var context = new PrincipalContext(ContextType.Domain, "crivelli.adv"))
        {
            var result = InternalSearch(filter);
            result.Groups = UserPrincipal.FindByIdentity(context, name)
                                         .GetGroups()
                                         .Select(g => new ActiveDirectoryGroupViewModel { Sid = g.Sid, Name = g.Name, Description = g.Description })
                                         .ToList();
            return result;
        };
    }

    /// <summary>
    /// Traz um usuário do AD por Sid (security identifier).
    /// </summary>
    /// <param name="sid"></param>
    /// <returns></returns>
    public static ActiveDirectoryUserViewModel GetADUserBySid(String sid)
    {
        var filter = "(&(objectClass=user)(objectCategory=person)(objectSid=" + sid + "))";
        return InternalSearch(filter);
    }

    /// <summary>
    /// Método auxiliar para montar pesquisas do AD.
    /// </summary>
    /// <param name="filter"></param>
    /// <returns></returns>
    static ActiveDirectoryUserViewModel InternalSearch(String filter)
    {
        using (DirectoryEntry entry = new DirectoryEntry("LDAP://meudominio.com"))
        {
            DirectorySearcher search = new DirectorySearcher(entry);
            // search.Filter = "(&(objectClass=user)(l=" + name + "))";
            search.Filter = filter;
            search.PropertiesToLoad.AddRange(new string[] {"samaccountname", "mail", "usergroup", "department", "displayname", "cn", "givenName", "initials",
                "sn", "homePostalAddress", "title", "company", "st", "l", "co", "postalcode", "telephoneNumber", "otherTelephone", "facsimileTelephoneNumber", "mail",
                "extensionAttribute1", "extensionAttribute2", "extensionAttribute3", "extensionAttribute4", "extensionAttribute5", "extensionAttribute6",
                "extensionAttribute7", "extensionAttribute8", "extensionAttribute9", "extensionAttribute10", "extensionAttribute11", "extensionAttribute12",
                "whenChanged", "whenCreated", "thumbnailPhoto", "objectSid", "objectGUID"}
            );

            foreach (SearchResult sResultSet in search.FindAll())
            {
                return new ActiveDirectoryUserViewModel
                {
                    Sid = new System.Security.Principal.SecurityIdentifier((byte[])sResultSet.Properties["objectSid"][0], 0),
                    // Guid = GetProperty(sResultSet, "objectGUID"),
                    DisplayName = GetProperty(sResultSet, "displayname"),
                    Email = GetProperty(sResultSet, "mail"),
                    Mapped = true,
                    UserName = GetProperty(sResultSet, "samaccountname"),
                    FirstName = GetProperty(sResultSet, "givenName"),
                    Surname = GetProperty(sResultSet, "sn"),
                    VoiceTelephoneNumber = GetProperty(sResultSet, "telephoneNumber"),
                    JobTitle = GetProperty(sResultSet, "title"),
                    Department = GetProperty(sResultSet, "department"),
                    Photo = sResultSet.Properties["thumbnailPhoto"][0] as byte[]
                };
            }
        }

        return new ActiveDirectoryUserViewModel();
    }

    /// <summary>
    /// Trz todos os grupos do AD.
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<ActiveDirectoryGroupViewModel> GetAllGroups()
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
        PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

        foreach (var found in srch.FindAll())
        {
            yield return new ActiveDirectoryGroupViewModel
            {
                Name = found.Name,
                Sid = found.Sid,
                Description = found.Description
            };
        }
    }

    /// <summary>
    /// Traz um grupo do AD por Sid (security identifier).
    /// </summary>
    /// <param name="sid"></param>
    /// <returns></returns>
    public static ActiveDirectoryGroupViewModel GetGroup(String sid)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
        var search = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid);

        if (search != null)
        {
            return new ActiveDirectoryGroupViewModel {
                Name = search.Name,
                Description = search.Description,
                Sid = search.Sid
            };

            /* foreach (Principal p in search.GetMembers())
            {
                Debug.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
            } */
        }

        return null;
    }

    /// <summary>
    /// Método interno para tratamento de propriedade do AD.
    /// </summary>
    /// <param name="searchResult"></param>
    /// <param name="PropertyName"></param>
    /// <returns></returns>
    private static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }
}

No meu caso, essa solução atende a um sistema ASP.NET MVC (por isso usa ViewModels), mas você pode criar outras classes com outros nomes, se preferir:
public class ActiveDirectoryUserViewModel
{
    [DisplayName("SID")]
    public SecurityIdentifier Sid { get; set; }
    [DisplayName("Guid")]
    public String Guid { get; set; }
    [DisplayName("Login")]
    public string Login { get; set; }
    [DisplayName("Endereço de E-Mail")]
    public string Email { get; set; }
    [DisplayName("Nome de Usuário")]
    public string UserName { get; set; }
    [DisplayName("Nome de Exibição")]
    public string DisplayName { get; set; }
    [DisplayName("Mapeado?")]
    public bool Mapped { get; set; }
    [DisplayName("Unidade Organizacional")]
    public string OrganizationalUnit { get; set; }
    [DisplayName("Primeiro Nome")]
    public string FirstName { get; set; }
    [DisplayName("Nome do Meio")]
    public string MiddleName { get; set; }
    [DisplayName("Sobrenome")]
    public string Surname { get; set; }
    [DisplayName("Telefone")]
    public string VoiceTelephoneNumber { get; set; }
    [DisplayName("Cargo")]
    public String JobTitle { get; set; }
    [DisplayName("Departamento")]
    public String Department { get; set; }
    [DisplayName("Foto")]
    public byte[] Photo { get; set; }

    [DisplayName("Grupos")]
    public List<ActiveDirectoryGroupViewModel> Groups { get; set; }
}

public class ActiveDirectoryGroupViewModel
{
    [DisplayName("Identificador de Segurança")]
    public SecurityIdentifier Sid { get; set; }
    [DisplayName("Nome")]
    public String Name { get; set; }
    [DisplayName("Descrição")]
    public String Description { get; set; }
}

O uso é bastante simples:
var ActiveDirectoryInfo = ActiveDirectoryHelper.GetADUserByLogin("DOMINIO\\usuario");
var listaDeUsuarios = ActiveDirectoryHelper.GetADUsers();


text:
Q: Common, accessible filesystem with very high filename size limit? I need to extract an archive that contains files whose names are longer than 256 characters. Every common filesystem I have tried (ntfs, ext3, ext4) has a limitation on filename size at 255 or 256 bytes. Is there a filesystem I can easily use in a Debian system (mkfs, mount, etc) that helps me get around this limitation?

A: Looking at this comparison of filesystems, it looks like the only one shipped with Debian that supports filenames longer than 256 characters is the (slightly notorious) reiserfs.
You can create and mount a new 100MB filesystem without needing to use a separate device like this:
# apt-get install reiserfsprogs
# dd if=/dev/zero of=/home/username/reiser-filesystem bs=1048576 count=100
# mkfs.reiserfs -f /home/username/reiser-filesystem
# mount -o loop /home/username/reiser-filesystem /mnt


text:
Q: Column is invalid in the select list when selecting count of children rows I have a parent table A(id,fld1,fld2), and child table B(id,parentId,fld1, fld2)
I want to select A.* and the count of the children rows
my query is:
SELECT A.*, COUNT(B.parentId)
INNER JOIN A ON B.parentId = A.id
GROUP BY B.parentId

but I'm getting:

Column 'A.id' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause.

A: Here's another way:
SELECT A.*, B.cnt
FROM A
CROSS APPLY (SELECT COUNT(*) As cnt
             FROM B
             WHERE B.parentId = A.id
            ) As B

A: Old fashion (correlated subquery):
SELECT A.*, (SELECT COUNT(*) As cnt
             FROM B
             B.parentId = A.id
            ) As cnt
FROM A


text:
Q: Markov Chain from Martingale The two parts to this problem show how processes can be characterized using martingales. In each part, let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space and let $\{\mathcal{F}_n\}$ be a filtration. Let $E$ be a finite or countable collection of points and $P=(p_{ij})=(p(i,j))$ be an $E\times E$ stochastic matrix. For each bounded function $f$ on $E$ define
$$Af(i)=\sum_j(f(j)-f(i))p(i,j)=\sum_jf(j)p(i,j)-f(i)$$
Let $f$ be a bounded function on $E$. Define the process $M$ such that $M_0=0$ and for $n\in \mathbb{N}$,
$$M_n=f(Z_n)-f(Z_0)-\sum_{k=0}^{n-1}Af(Z_k)$$
1) Let $Z=\{Z_n:n=0,1,2,...\}$ be a Markov chain having initial distributions $\mu$ and transition probabilities $P$; i.e., $\mathbb{P}(Z_{n+1}=j|\mathcal{F}_n)=p(Z_n,j)$.
The first part was to show that $M$ is a Martingale (what I typed above), which I already did. I am struggling with the second part, which says:
Now suppose that $Z=\{Z_0,Z_1,Z_2,...\}$ is a sequence of random variables such that $M$ is an $\{\mathcal{F}_n\}$-martingale for every bounded function $f$ on $E$, where $M_n$ is defined above and $\mathbb{P}(Z_0=i)=\mu(\{i\})$. Show that $Z$ is a Markov chain having transition probability matrix $P$.
I know I need to show that
$$\mathbb{P}(Z_0=i_0,Z_1=i_1,...,Z_n=i_n)=\mu_{io}p_{i_0i_1}...p_{i_{n-1}}p_{i_n}$$
that is, that every state is independent up to n.
My first idea is that since $M$ is a Martingale and $\mathbb{E}[M_n|\mathcal{F}_{n-1}]=M_{n-1}$, we can transfer that to $Z_n$, namely, $\mathbb{E}[Z_n|\mathcal{F}_{n-1}]=Z_{n-1}$ but after that I don't really know how to proceed.
I would appreciate any help!
Thanks.

A: Given any bounded function $f$, we have
\begin{align*}
\mathbb E[f(Z_n)|\mathcal F_{n-1}] &= \mathbb E[M_n | \mathcal F_{n-1}] + f(Z_0) + \sum_{k=0}^{n-1}Af(Z_k) \\
&= M_{n-1} + f(Z_0) + \sum_{k=0}^{n-1}Af(Z_k) \\
&= f(Z_{n-1}) + Af(Z_{n-1}) \\
&= \sum_j f(j)p(Z_{n-1},j).
\end{align*}
Apply this for the function $f=\mathbf 1_{\{z\}}$ to obtain
$$ \mathbb P(Z_n = z|\mathcal F_{n-1}) = \mathbb E[f(Z_n)|\mathcal F_{n-1}] = \sum_jf(j)p(Z_{n-1},j) =p(Z_{n-1},z).$$
This shows $\{Z_n\}$ is a Markov chain with transition probabilities $p$.


text:
Q: Wordpress Contact Form don't send files in attachment I've got a little problem with CF7. The plugin works good in wordpress, but when I put the file field on the form, the wordpress doesn't send the e-mail, if I take off the file field, it works perfectly.
EDIT -----------
Form HTML:

Seus Dados de Contato

          [text* your-name watermark "Nome:"]
          [email* your-email watermark "E-mail:"]
          [tel* tel-987 id:telId class:telClass watermark  "Telefone:"]

          [textarea your-message watermark "Mensagem:"]

Tipo de Seguro Desejado

          [checkbox* tipo-seguro id:tipo-seguro class:tipo-seguro label_first use_label_element "seguro de automóvel" "seguro de motos" "consórcio" "seguro de vida" "planos de saúde" "seguro de caminhões" "seguro prestamista" "carta verde" "previdência privada" "seguro viagem"]

          [text outros id:outros class:outros watermark  "Outros Seguros Desejados:"]

Enviar arquivo

[file arquivo limit:3000000 filetypes:jpg|doc|png|pdf id:arquivo class:arquivo]

[submit id:cotar class:cotar "solicitar cotação"] <input type="reset" value="limpar campos" />

IN MESSAGE BODY:

Cotação do Web Site

Nome:
          [your-name]

E-mail:
          [your-email]

Telefone:
          [tel-987]

Mensagem:
         [your-message]

Outros seguros desejados:
         [outros]

Arquivo:
 [arquivo]

       Tipo de Seguro Desejado

 [tipo-seguro]

IN ATTACHMENT FIELD:
[arquivo] // <-- this is my input file field

Someone already had the same problem?


text:
Q: Is throwing a temporary value as reference undefined behavior? To my surprise, std::runtime_error only has a const std::string& constructor, but no value constructor. Thus I am wondering if throw std::runtime_error("Temporary" + std::to_string(100)); is defined. After all we are creating an exception object that refers to a temporary object inside the scope of a function that immediately exits (as we throw out of it). Further investigation showed that while returning a constant reference to a temporary value immediately causes a segfault on my system, throwing one doesn't:

const std::string& undefined_behavior() {
    return "Undefined " + std::to_string(1);
}

void test() {
    throw std::runtime_error("Hello : " + std::to_string(2));
}

void test2() {
    const std::string& ref = "Hello : " + std::to_string(3);
    throw ref;
}

int main(int argc, char** argv) {
    //std::cout << undefined_behavior() << std::endl;
    try {
        test();
    } catch(const std::runtime_error& ex) {
        std::cout << ex.what() << std::endl;
    }
    try {
        test2();
    } catch(const std::string& ref) {
        std::cout << ref << std::endl;
    }
}

On my system, undefined_behavior() crashes immediately but test() and test2() run fine.
While I know the call to undefined_behavior() is undefined behavior, is test() and test2() undefined? If not, do thrown values get a specfied treatment?
And if they are all undefined but happened to work on my computer by accident, what is the proper way to throw an exception with a variable message?

A: The const std::string& constructor doesn't cause the exception object to store a reference to the passed std::string. std::runtime_error will make an internal copy of the passed string (although the copy will be stored in an usual way, probably reference-counted in an allocation external to the exception object; this is to give better exception guarantees when the exception object is copied, which the standard requires).
A function taking a const lvalue reference doesn't usually mean that it takes ownership or stores a reference to the object.
Prior to C++11 there was no reason to not use a const reference here, since it was always more efficient than passing by-value. With C++11 move semantics that changed and it is true that usually these kind of constructors had rvalue reference variants added with C++11, so that passing a temporary std::string object to the constructor would allow more efficient move-construction instead of copy-construction.
My guess is that this simply never was done for the exception classes because the performance of their construction should not be important in comparison to the overhead of actually throwing the exception.
So in test()'s case a temporary string object is created from the + operation, which is passed to the constructor and the exception object will make a copy of it. After the initialization of the exception object the temporary string is destroyed, but that is not a problem, since the exception object stores/references a copy.
In test2() the same would apply if you had written throw std::runtime_error(ref). However, here a reference is bound immediately to the temporary object materialized from the return value of +. This causes its lifetime to be extended to that of the reference variable. Therefore again, the temporary lives long enough for the std::runtime_error to make a copy from it.
But since you write simply throw ref that is not exactly what happens. throw ref will throw a std::string, because that is the type of the ref expression. However, throw doesn't actually use the object referenced by the expression as exception object. The exception object is initialized from the operand of the throw expression. So here, the exception object will be another std::string object (in unspecified storage) which will be initialized from the temporary that ref refers to.
undefined_behavior() has undefined behavior when the return value is used, because the temporary std::string object materialized from the + return value and which the return value of undefined_behavior() references is not lifetime-extended. Although it is again immediately bound by a reference, the lifetime-extension rule specifically doesn't apply to objects bound to a reference in a return value initialization. Instead the temporary is destroyed when the function returns, causing the function to always return a dangling reference.

A: It is not undefined behavior.

In test1(), the constructor of std::runtime_error makes an internal copy. There is even a note on this at cppreference:

Because copying std::runtime_error is not permitted to throw
exceptions, this message is typically stored internally as a
separately-allocated reference-counted string. This is also why
there is no constructor taking std::string&&: it would have to
copy the content anyway.

In test2() there is no std::runtime_error involved. Instead, as you can read e.g. here, in the following statement
throw expr;

the exception object is copy-initialized from expr. So there is a copy made of that temporary string also in this case.


text:
Q: Distributivity of ! over? Has anyone studied a variant of linear logic, or of its semantic counterpart (exponential modalities on linearly distributive categories / $\ast$-autonomous categories / polycategories) for which there is a distributive law
$$!? \to ?!$$
Presumably it would need to interact sensibly with the (co)monoidal structure of ! and ?.  I haven't thought about whether there is a nice sequent calculus or resource interpretation.  I ask for two reasons:

*

*Such a distributive law should imply that there is a "mixed Kleisli category" whose morphisms from $A$ to $B$ are the morphisms $!A \to ?B$.  This would be more symmetrical and pleasing than the usual translation of classical logic involving morphisms $!?A \to ?B$.

*In $\rm Chu(Cat,Set)$ I believe there is such a distributive law, or at least a pseudo-distributive law, and a morphism $!A\to ?B$ should be precisely a profunctor from $A^+$ to $B^-$.  So this would give a nice way of recovering $\rm Prof$ from $\rm Chu(Cat,Set)$.

A: I would tend to say "no".
However, besides my comment above, which is not very pertinent, let me mention the paper Combining effects and coeffects via grading, by Marco Gaboardi, Shin-ya Katsumata, Dominic Orchard, Flavien Breuvart and Tarmo Uustalu.  They consider "graded" monads and comonads, which include usual monads and comonads as the special case in which the grading is trivial (I don't know who introduced these first, I learned of graded comonads from this note by Paul-André Melliès).  The programming language underlying their work is linear and their comonads are graded in a semiring (rather than just a monoid) so that they are a generalization of the exponential modality $!(-)$ of linear logic (the additive structure of the semiring grades weakening/contraction, i.e. the monoidal structure of the comonad, while the multiplicative structure of the semiring grades the actual comonad structure, i.e., the counit and the comultiplication).  They then study graded versions of the usual distributive law between monads and comonads in order to account for the simultaneous presence of "quantitative" effects and coeffects in programming languages (e.g., not just tell whether a program may raise an exception but tell, if possible, how many exceptions it will raise, or whatever.  This is what the increased expressiveness given by the grading is meant to be used for).
So, forgetting the grading, i.e., if we grade everything with the trivial semiring and the trivial monoid, we are close to what you describe, but not quite: while the trivially graded version of their comonad is, indeed, the $!(-)$ modality of linear logic, the $?(-)$ modality does not fit into their axiomatization, because the trivially graded version of their monad is necessarily strong, and $?(-)$ is not a strong monad.  So, strictly speaking, this work says nothing about the distributive law you are looking at.
I skimmed through the references given by Gaboardi et al. in relation with distributive laws and none of them seems to mention linear logic.  This supports my belief that no one has ever introduced/studied the variant of linear logic you mention... but of course I can't be sure!


text:
Q: ASP.NET MVC Leave a Copy of Email on Server I have a ASP.NET MVC 4 project with EF. I' m using System.Net.Mail to send emails programmatically.
MailMessage msg = new MailMessage();
msg.From = new MailAddress("JohnDoe@gmail.com", "John Doe");
msg.To.Add(new MailAddress("janedoe@gmail.com"));
msg.Subject = "Hi.";
msg.Body= "Aleluia";
var smtp = new SmtpClient("mail.johndoe.com", 999);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("JohnDoe@gmail.com", "johnspass");
smtpclient.Send(msg);

Q : How can I save a copy of this email in John Doe's Sent Items ? If I have Outlook can I use this ?
Q2 : How can I elaborate this email's body(to add a image in the left top corner, to add a bolded text) ?

A: I'm not sure if you can achieve this from a website, unless you have a way to manipulate a backend mail server and have access to manipulate users mailboxes.
The way outlook does this is by pushing any new sent email to the Sent Items folder and then it syncronizes the content with Exchange Server.
I also think Exchange server provides the API to achieve this behavior but your website would have to run under Windows Authentication to access and manipulate each user mailbox. I dont think is a good idea to give access to individual mailboxes to a global account (in this case the website pool identity account). You also might want to look into Exchange Web Services (2007 or greater).
This has been my experience with Exchange Server, I might be unaware of another allowed behavior and dont know anything about other mail servers in terms of APIs.


text:
Q: Docker Wordpress container with custom php.ini file settings I'm running Wordpress (and PHPMyAdmin and MySQL) in a Docker container, and I need to make a change to increase the maximum uploadable file size for PHPMyAdmin
I researched a number of solutions and found a suggestion to create a custom uploads.ini file and then include this file in the docker-compose file.
So I have this:
uploads.ini
file_uploads = On
memory_limit = 64M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 600

docker-compose.yml
version: '3'

services:
  # Database
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    networks:
      - wpsite
  # phpmyadmin
  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    restart: always
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: password
    networks:
      - wpsite
  # Wordpress
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - '8000:80'
    restart: always
    volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
    networks:
      - wpsite
networks:
  wpsite:
volumes:
  db_data:

I have included the uploads.ini file in the volumes for wordpress
volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini

But sadly after running the docker-compose and opening localhost:8080 to go to PHPMyAdmin I still only have a maximum file upload size of 2m, not the 64m in my custom file

A: You want increase the maximum uploadable file size for PHPMyAdmin, but uploads.ini you add for your wordpress container)
add volume for phpmyadmin container and you'll be happy=)
# phpmyadmin
phpmyadmin:
depends_on:
  - db
image: phpmyadmin/phpmyadmin
volumes:
 - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
restart: always
ports:
  - '8080:80'
environment:
  PMA_HOST: db
  MYSQL_ROOT_PASSWORD: password
networks:
  - wpsite

A: You can pass the upload limit to the phpmyadmin docker container with an ENV variable
Example
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: phpmyadmin
depends_on:
  - mysql
environment:
  - UPLOAD_LIMIT=512M
  - PMA_HOST=mysql
  - PMA_PORT=3306
  - PMA_ARBITRARY=1
ports:
  - "8888:80"

A: You can try to rebuild your image, but like this.
Add this somewhere in your your Dockerfile.
This way you would be sure its not some kind of permission trouble(which I think it is)
  COPY ./uploads.ini /usr/local/etc/php/conf.d

A: According to this answer you need to set absolute path to mount single file. So add a ${PWD} before files to be mounted.
Your volume part would be like:
volumes:
  - ${PWD}/uploads.ini:/usr/local/etc/php/conf.d/uploads.ini

A: You can use this plugin for the upload max size increase
https://wordpress.org/plugins/upload-max-file-size/


text:
Q: Remove specific cart item based on minimal subtotal in Woocommerce cart & checkout In Woocommerce, I am trying to auto remove a gift product from cart if cart item is less than 300,000 dongs.
Here is my code:
add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
// Run only in the Cart or Checkout Page
     global $woocommerce;
     $current =  WC()->cart->cart_contents_total;
    $min_amount= 300000;
     $prod_to_remove = 357;
if ( $current < $min_amount) {
if( is_cart() || is_checkout() ) {

    // Cycle through each product in the cart
    foreach( WC()->cart->cart_contents as $prod_in_cart ) {
        // Get the Variation or Product ID
        $prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
        // Check to see if IDs match
        if( $prod_to_remove == $prod_id ) {
            // Get it's unique ID within the Cart
            $prod_unique_id = WC()->cart->generate_cart_id( $prod_id );
            // Remove it from the cart by un-setting it
            unset( WC()->cart->cart_contents[$prod_unique_id] );
         wc_add_notice( __( 'Quà tặng của bạn đã bị xóa khỏi giỏ hàng vì ' ), 'notice' );
        }
    }
}
}}

But the problem is that it does not work with product variations.
Any help is appreciated.

A: Uptaded (to handle multiple items to be removed).
Try the following revisited code, that will work with product variations too in a better way:
add_action( 'woocommerce_check_cart_items', 'conditionally_remove_specific_cart_item' );
function conditionally_remove_specific_cart_item() {
    ## -- Settings -- ##
    $min_required   = 300000; // The minimal required cart subtotal
    $items_to_remove = array( 446, 27 ); // Product Ids to be removed from cart

    // Only if cart subtotal is less than 300000
    if( WC()->cart->cart_contents_total >= $min_required )
        return;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if( array_intersect( $items_to_remove, array( $cart_item['variation_id'], $cart_item['product_id'] ) ) ) {
            // Remove cart item
            WC()->cart->remove_cart_item( $cart_item_key );

            // Add a custom  notice
            wc_add_notice( sprintf(
            __( "Your gift has been removed from the cart because its requires a minimal cart amount of %s", "woocommerce" ),
            $min_required ), 'notice' );
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.
In cart page:

In checkout page:


text:
Q: Contraction mapping with no fixed point I am interested in constructing the following "counter-example" to the Banach's fixed point theorem.
Let $K=$ {$ g\in L_1: \|g\|=1, g(\cdot)\ge0 $}.
 Clearly, $K$ is not a compact and $K$ is  not   closed.
My A question is: is it possible to construct a [edit] nonexpansive mapping $f: K\to K$  with no fixed point? (   i.e. a mapping $f$ such that [edit] for all $x\neq y\in K$ one has $\|f(x)-f(y)\| <  \|x-y\|$. )

A: There need not be a fixed point.  First note that by composing with a conditional expectation onto the closed span of indicator functions of disjoint sets it is sufficient to build an example on $W:=\{x\in \ell_1 : x_i \ge 0, \sum x_i =1\}$. Given $x\in W$, define $y=Tx \in W$ by $y_1=0$, $y_2 = x_1/2$, and, for $k\ge 2$, $y_{k+1} = y_k/2 + x_{k+1}/2$. It is obvious that $T$ is nonexpansive. The inequality $\|Tx-Ty\|<\|x-y\|$ when $x\not= y$ follows from the fact that if $x\not= y$ there are coordinates $i$ and $j$ s.t. $x_i<y_i$ and $x_j>y_j$.


text:
Q: Delphi 7 ISAPI WebBroker file upload I am trying to accept file uploads in a Delphi 7 Webbroker CGI.
I'm using Shiv Kumar's TMsMultipartParser, but I have a problem with Chrome. I can't access the parsed data (surprisingly, Explorer works fine).
This is my code:
with TMsMultipartFormParser.Create do
begin
    Parse(Request);

    lsExternalID:=ContentFields.Values['external_id'];

    if (lsExternalID='') then
        raise Exception.Create('No external ID');

    for i := 0 to Files.Count -1 do
    begin
        lsFileName:=files[i].FileName;
        //Rename file using external ID (not included for simplicity)
        Files[i].SaveToFile(lsFilename);
    end;
    Response.Content := 'OK';
    free;
end;

As suggested here, I tried to use http://www.mrsoft.org/Delphi/MultipartParser.pas but I can't compile it. It uses a unit called UniversalUtils that I can't find anywhere.
I know this is a very obsolete technology. Almost all references to it have already disappeared from the web (believe me, I have searched). Buy any help would be deeply appreciated.
Thanks.

A: I finally solved my problem, thanks to @mrabat.
This project started in Delphi 5. It was later upgraded to Delphi 7 (it can't be upgraded further, because many parts can't support Unicode strings, we use ANSI).
We were using Shiv's TMsMultipartParser because Delphi 5 didn't have any parser included.
Delphi 7 has TMultipartContentParser in unit ReqMulti.pas, and it works perfectly.
For anyone that need an example, I'll post my working code:
with TMultipartContentParser.Create(Request) do
begin
    lsExternalID:=ContentFields.Values['external_id'];
    if (lsExternalID='') then
        raise Exception.Create('No external ID');

    for i := 0 to Request.Files.Count -1 do
    begin
        lsFileName:=Request.Files[i].FileName;
        //Rename file using external ID (not included for simplicity)
        TMemoryStream(Request.Files[i].Stream).SaveToFile(lsFilename);
    end;
    Response.Content := 'OK';
    Free;
end;

A: I wrote something similar once here:
https://github.com/stijnsanders/xxm/blob/master/Delphi/common/xxmParams.pas#L159
but that may be tightly coupled with SplitHeaderValue that parses the header lines, and TStreamNozzle that throttles incoming data. (and TXxmReqPar... objects, and IXxmContext...)
(Of course you're warmly welcomed to accept file uploads with xxm...)


text:
Q: Bot reaction to SPECIFIC words I'm having an issue trying to get my bot to respond to specific words. For example, having the words 'her', 'he', 'shop', and 'hop' trigger the bot to say "test". I've added these to a loop/list however the bot triggers the response on ANY word that has a sequence of the above letters. If someone says 'theater' the bot will respond because "tHEater". Here is the code I tried:
triggers = ['he', 'she', 'hop', 'shop']

for word in triggers:
    if word in message.content:
        await message.channel.send("test")
        break

message.content == "she", etc does not work because this would only trigger on if someone ONLY typed 'she'.
What is happening? Is there a way for it to trigger on the specified sequence of letters?


text:
Q: Custom ModelBinder which converts only certain parts of the posted Data let's say we have the following Method in our WebService:
ActionResult SomeMethod(int primitiveValue, List<MyComplexValue> complexValues)
{
//...
}

class MyComplexValue
{
    public int TransformedValue { get; set; }
}

The WebClient posts the following JSON data to our method:
{ primitiveValue: 17, complexValues: [ { Value: 1}, { Value: 2} ]}

I now want to implement a custom ModelBinding, which only transforms the "complexValues" parameter into my own List of MyComplexValue-instances.
Is that possible?
The DefaultModelBinder should still take care of all the primitive values (such as the parameter "primitiveValue").
I tried to implement a Custom ModelBinder the following way:
public class CustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string incomingData = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
        if (incomingData == null)
            return null;

        //Transform passed object list to ComplexValue List
    }

}

//...

ActionResult SomeMethod(int primitiveValue, [ModelBinder(typeof(CustomModelBinder ))] List<MyComplexValue> complexValues)
{
//...
}

The problem is, that GetValue always returns null. I would like it to return the string "[ { Value: 1}, { Value: 2} ]", so that I can deserialize this JSON myself and take care of the conversion myself.
Any ideas?
Thanks!


text:
Q: Unity Remote 4 is connected but Shows black screen When I press play in the editor the scene runs for both the Game view in the editor and my phone.
But my phone just shows a black screen. It functions well. Meaning I can interact with the scene from the phone. I can pan, zoom, click buttons but blindly.
The model is GT-S7582. I'm using the latest ADB version. Phone is connected via USB and "USB debugging" is enabled and "Allow mock locations" is enabled. Unity version is 5.4.0b18 on Ubuntu 14.04 64 bit


text:
Q: Flutter Firebase Authentication error on Ios call  await firebaseAuth.signInAnonymously();  causes error:
[firebase_auth/admin-restricted-operation] ADMIN_ONLY_OPERATION.
Email auth provider and Anonymous option in Firebase console are enabled.
Error happens only on iOS, on Android it's ok.
How this can be fixed?

A: You haven't the correct GoogleService-Info.plist in your project.
Read the iOS installation: https://firebase.flutter.dev/docs/installation/ios


text:
Q: Cross Domain session sharing in django I have two websites abc.com and xyz.com and I am logged in in abc.com.
I want the same session available in xyz.com also.
Please help me to maintain same session in two different domains using django framework.


text:
Q: Counting frequency of a sequence within a vector Let's say I have a binary vector of length N, and I'm looking for the frequency of each of the following 16 sequences in that vector:
0000, 0001, 0010, 0011, ..., 1111

What is the easiest way to count these frequency of each of these sequences in the vector?  Ideally, I'd like to know how to do this in MatLab.

A: A simple way to solve this is to convert the binary numbers to decimal numbers, and then use either hist or accumarray to count occurences. I start out with reshaping the array into an (N-3)-by-4 array, which allows vectorizing all calculations.
%# make up some test data
data = [0 0 1 1 0 1 0 1 1 1 1 1 0 0 1 1];

%# reshape into a (N-3)-by-4 array
%# idx is [1 2 3 4;2 3 4 5;...]
idx = bsxfun(@plus,(1:length(data)-3)',0:3); %'#
data = data(idx);

%# convert binary numbers to decimals
%# use matrix multiplication
decData = data * [8;4;2;1];

%# count number of occurences - possible values are 0 through 15
counts = hist(decData,0:15);

counts(1) counts the number of times the sequence 0 0 0 0 has appeared in the list.

A: Those are the numbers 0x0 to 0xF, just ++ them as indexes into an array of size 0xF.  Sum array elements, and A[i]/N is your frequency.

A: count = zeros(1,16);
vector = [1 0 0 1 1 1 1 0 0];
N = length(vector);

for ii = 1:(N-3)
    cur_seq = vector(ii:ii+3);        % Grab the running set of four entries
    cur_num = cur_seq*[8; 4; 2; 1];   % Convert these entries to non-binary.

    % Update the count of the sequence that has cur_num
    % as its non-binary integer representation. Note that
    % you must use cur_num+1 as the index since Matlab is
    % 1-based, but the integers from your sequences are 0
    % through 15.

    count(cur_num+1) = count(cur_num+1) + 1;
end

Now count(1) counts occurrences of [0,0,0,0], and count(2) counts occurrences of [0,0,0,1] and so on.

A: Let the data and block length be defined as
x = [ 1 0 1 0 0 0 0 0 1 1];
M = 4;

Then the result can be obtained with a single line as follows:
result = histc(conv(x, 2.^(0:M-1), 'valid'), 0:2^M-1);

In this example,
result =
     2   1   0   1   1   0   0   0   1   0   1   0   0   0   0   0

meaning there were 2 ocurrences of [0 0 0 0], 1 occurrence of [0 0 0 1] etc.
How this works:

*

*Compute a convolution (using conv) with powers of 2, to find the decimal representation of each sliding length-M binary number.

*Count occurrences of each number obtained in step 1 (using histc).

A: If a is holding your data:
c = []
for el = a,
  c = [c, sum(a==el)];
end

This is quadratic, but will have the counts at the same indices as a. It would work also if you don't know the range in advance.


text:
Q: Loading an .obj with JOGL I have found may tutorials on loading an obj, but nothing on how to load it and use it with java, anyone have links to any useful tutorials?

A: The closest that I could find were:

*

*JOGL-ES Chapter 2 - Loading OBJ Models

*OBJ File Format

*OBJ Loader, Renderer Independent
Keep in mind that JOGL is a very low-level API.  Some of the higher-level APIs (JMonkeyEngine, and Java3D) have sophisticated APIs built in for handling this sort of thing.  With JOGL, you will be doing much of the work yourself.  Obviously, there are advantages and disadvantages to each approach.

A: Not a tutorial, but how about some sample code?  Unfortunately it uses the "Fixed Function Pipeline" rather than using the new "do everything with shaders" approach, but I like to think the code is clear.
http://darksleep.com/oObjLoader/
Also, I should note that it does use VBOs and not direct rendering or display lists, so it is fairly efficient.


text:
Q: How to stop thread Handler in Android? I just begun with a simple thread handler program on Android. The code works. The only part is on how to shut down the handler. I am trying in vain to close the handler onPause() but it simply keeps running. Any suggestions?
Here is the code:
My Main Activity thread:
package com.test.prog;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class AndroidThreadProgv1Activity extends Activity {

    private Handler DataHandler;

    private DataUpdater du;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /* Initialize handler to allow UI updating in other threads */
        DataHandler = new Handler();

        startDataUpdater();

    }

    public void onPause(){
        super.onPause();
        du.stopConnection();
    }

    private void startDataUpdater(){
        System.out.println("In startDataUpdater");
        du = new DataUpdater(DataHandler,(TextView) findViewById(R.id.textView1));
        du.start();
    }

}

DataUpdater.java:
package com.test.prog;

import java.io.IOException;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;

/*
 * Data updater thread.  Updates the display with the response.
 */
public class DataUpdater extends Thread{

    /*Handler for the UI update*/
    private Handler dataRefreshHandler;

    /*The UI text displaying the data*/
    private TextView dataLabel;

    /*data value*/
    private int data = 0;
    /*data update rate in ms*/
    private static final int dataUpdateRate = 2000;

    private boolean stoppedFlag= false;

    public DataUpdater(Handler handler, TextView tv){
        this.dataRefreshHandler = handler;
        this.dataLabel = tv;
    }

    public void stopConnection()
    {
        if(this.dataRefreshHandler != null) {
            this.dataRefreshHandler.removeMessages(data); // Remove a delayed message
            System.out.println("In stopConnection");
            /*
           if(!stoppedFlag){
                this.dataRefreshHandler.getLooper().quit(); // Warning
                stoppedFlag = true;
            }
            */
        }
    }

    @Override
    public void run(){
        try {
            while(true){
                System.out.println("In run");
                data = data + 1;
                updateData();
                Thread.sleep(dataUpdateRate);
            }

        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /*
     * Calls the UI Handler and updates the display
     */
    private void updateData(){
        dataRefreshHandler.post(new Runnable() {
            public void run() {
                if(data==0)
                {
                    dataLabel.setText("Value not known");
                }
                else
                {
                    System.out.println("In update");
                    dataLabel.setText("Value="+data);

                }
            }
        });
    }
}

A: Your "run" method in dataUpdater has a while(true) loop. You never check for any exit condition so it will never stop. What you could do is include a volatile flag in DataUpdater (initially set to true) and have stopConnection set it to false. Your while loop in run can check that flag instead of just looping infinitely.
To make sure your DataUpdater is running whenever your activity is running:
Move the call to startDataUpdater(); from onCreate to onResume (Android always calls onResume after onCreate so this will ensure that you are always calling startDataUpdater on creation as well as on resuming after pause).
Change your run method in DataUpdater to look like this:
public void run(){
   isRunning = true; // isRunning should be declared as a "private volatile boolean"
    try {
        while(isRunning){
            System.out.println("In run");
            data = data + 1;
            updateData();
            Thread.sleep(dataUpdateRate);
        }
    }

A: You can make user of the Looper, instead of using while(1) which is CPU hogger.
For looping back , you can post the messages back to same handler in the looper.
For stopping when ever you want just post the runnable Looper.myLooper.stop() in the run() method of the runnable to the looper.
Looper is more efficient than the While(true)


text:
Q: PowerShell sript to set IIS environment variable How can I automate the following steps by using PowerShell? :

*

*Go to IIS and choose a website (website name will most likely be passed down in script as a parameter)

*Go Inside the Configuration Editor

*Choose the aspNetCore Section in the dropdown

*Go inside the environmnetVariables

*Add new Collection

*Create new environment varialbe

A: Thanks to Lex Li, Seems like Configuration Editor generates scripts automatically before savings. This has lead me to getting the final PS script to be:
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/WEBSITENAME'  -filter "system.webServer/aspNetCore/environmentVariables" -name "." -value @{name='EnvironmentVariableName';value='EnvironmentVariableValue'}


text:
Q: How to pass variables into SQL query using Jupyter Notebooks Python For Example:
%bq query -n qu

SELECT

    *

FROM

    Table

WHERE

    [passed in variable (column)] = true

Then i want to execute the query in a loop
for row in data:

  bq.execute qu(row[1])

Does something along these lines exist?
EDIT: I figured out a solution for anyone who comes across this question
For row in [dataset with your variables]:

   query = "SELECT * FROM DATASET WHERE {} = TRUE".format(variableData[0])

   tab = bq.Query(query)

   df = tab.execute(output_options=bq.QueryOutput.dataframe()).result()

   qu = [list(x) for x in df.as_matrix()]

   print(qu)

A: Here's a complete example showing Python variable substitution.
https://colab.research.google.com/notebook#fileId=0B7I8C_4vGdF6Mk1RMm1Fdm9EQVU
The notebook shows the following:

*

*Create a BigQuery table from some random CSV data.

*Query that table using the Pandas GBQ connector.

*Construct and execute a query against that table using Python variable substitution.


text:
Q: Online WYSIWYG XML editor Is there any open source online WYSIWYG Editor for various XML documents? I think the style could be added by XSLT, but if there is an editor, wich uses some other way to assign style to an XML file, I'm intrested.
EDIT: I've checked Xopus, Jaxe, Vex, Oxygen, Bitflux already, but none of them are matches the conditions above (not opensource, not online, etc)

A: WebJaxe is the online equivalent of Jaxe. It's actually more than that, since it has CMS features. As with Jaxe, you can change the look of XML elements in the editor with a config file. WebJaxe can use a PHP script and an XSLT transform to generate a website with the XML.


text:
Q: Make text fall below an image if it cannot be displayed with a certain width I have the following HTML code

Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts.

If the screen is wide enough, the texts display on the right of the image, which is good.
If the screen is narrow, the texts display below the image, which is good.
However, when the screen is in the transition stage (a little wider than the image width), the texts are narrowed displayed on the right of the image. How can I make sure the texts can occupy a min width of, say 30em, otherwise let it go under the image?

A: You can use media queries.
img {
   float: left;
}

@media only screen and (max-width: ???px) {
   img {
       float: none;
   }
}

Here is a fiddle.
UPDATE
If you want to manipulate the p element instead of removing float on the img, you can add clear style to p:
@media only screen and (max-width: ???px) {
    p {
        clear: left;
    }
}

Here is a sample fiddle.

A: UPDATED: Let the image float:left and the text display:table-cell then set a min-width (wich will be the breaking point) and a width for the text. But if you want a text block with a fixed size instead, just set its min-width and width with the same value. On the below snippet, click on 'full page' then resize the browser window to check the result.

* {
    font-weight: 600;
    color: orange;
    font-family: arial;
}

#image {
    width:400px;
    height:150px;
    float:left
}

#textbox {
    display: table-cell;
    width: 400px;
    min-width: 200px;
}

    Some texts. Some texts. Some texts. Some texts. Some texts.
    Some texts. Some texts. Some texts. Some texts. Some texts.

A: Here is a cleaner solution.
the html is

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Here is your css which makes the content span 100% if the width is under 500px.
.container {
    width:100%;
}

.pull-left {
   float: left;
}

.container--image, .container--content {
   display: block;
}

.container--image {
   margin-right: 20px;
}

.container--content {
   width: 50%;
}

@media only screen and (max-width: 500px) {
    .container--content {
        width: 100%;
    }
}

Here is the fiddle.

A: There is no real need to use media-queries. You may just add overflow: hidden to the
 element, with the desired threshold width as min-width.

img{
  float: left;
}
p{
  overflow: hidden;
  min-width: 50%;
}

Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts. Some texts.


text:
Q: Passing current date to select options So i have got several select options for months, days, years, hours, minutes and i am trying to insure the current time into them with javascript, these forms are being created by django and already have id's but nothing seems to be happening. Anyone know why?
{% if form.instance.id %}
      {% trans "Update" %} {{ form.instance }}
  {% else %}
      {% trans "Create event" %}
      <script>
        document.getElementById('id_start_0_day').value = (new Date()).format("dd");
      </script>
  {% endif %}

Example of one select
<select id="id_start_0_day" name="start_0_day">

A: If value is not present in the select you cannot select it, what you can do is, check if value is present if not add and select as below

$(document).ready(function() {

    var value = 2;

    if ($("#select option[value='"+value+"']") == null || $("#select option[value='"+value+"']").length == 0) {
         $("<option/>").attr("value", value).text(value).attr("selected", true).appendTo($("#select"));
    }

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
<option value="1">1</option>
</select>


text:
Q: On click run GET request inside JavaScript parsing a JavaScript variable. Laravel framework I have a dropdown checklist that manipulates an array inside JavaScript.
Once the dropdown checklist selection is complete.  The array is called uniqueYears.
function myFilter() {
var requestData = JSON.stringify(uniqueYears);

   console.log(requestData);
   //logs correct json object
   var request;

   request = $.ajax({
       url: "/admin/award/filter",
       method: "GET",
       dataType: "json",
       data: {data : requestData}
   });}

I would like to send that array to my controller. where it checks and returns all the items that satisfy those conditions
public function getReportByYear(Request $request){
  $awards = Award::all();
  $nominations = Nomination::all();
  $unique_Years = DB::select('SELECT EXTRACT(YEAR FROM created_at) AS uniqueYears FROM nomination group by uniqueYears  ');
  $countNoms = DB::select('SELECT EXTRACT(YEAR FROM created_at) AS uniqueYears, count(id) AS countID ,award_id from nomination group by award_id HAVING uniqueYears IN ');
  return view('admin.awardReport')->with('nominations', $nominations)->with('awards', $awards)->with('unique_Years' ,$unique_Years)->with('countNoms',$countNoms);
}

currently i am stuck with this error http://localhost/admin/award/filter?data=%5B%222014%22%2C%222015%22%5D 500 (Internal Server Error)
Any help getting past this error and getting to where i want to be would be appreciated !
here is the route i am using
Route::get('/admin/award/filter','AdminController@getReportByYear');


text:
Q: convert mutiple lists into a dictionary I'm not sure if this is possible, but is there a way to combine 3 lists into a dictionary so that the list name is the key and the list of items is the value?
Example:
Inputs:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

output:
dict = {
  'list1': ['a', 'b', 'c'],
  'list2': ['d', 'e', 'f'],
  'list3': ['g', 'h', 'i']
}

thanks

A: if you're able to define your list in its own function,
(so they are the only variables in the local function),
you can do this:
def loc():
  list1 = ['a', 'b', 'c']
  list2 = ['d', 'e', 'f']
  list3 = ['g', 'h', 'i']

  list_dictionary = (locals())

  print(list_dictionary)

loc()

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}

Otherwise, you may need to resort to something more like this:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

list_dictionary = {}
for i in ('list1', 'list2', 'list3'):
  list_dictionary[i] = locals()[i]

print (list_dictionary)

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}

source: https://stackoverflow.com/a/3972978/5411817

if your variable names are repetitive, as in the example, you can compose a list of strings for the variable names:
variable_names_as_strings = []
for i in range(1,4):
    variable_names_as_strings.append('list' + str(i))

Then create your dictionary:
for i in variable_names_as_strings:
  list_dictionary[i] = locals()[i]
print (list_dictionary)

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}

more info on locals() (also look up globals()):
https://www.programiz.com/python-programming/methods/built-in/locals
https://docs.python.org/3.3/library/functions.html#locals

A: list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

dictionary = dict()

dictionary['list1'] = list1
dictionary['list2'] = list2
dictionary['list3'] = list3

print(dictionary)

output:
{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}


text:
Q: Extracting Data From Python Classes I wrote a program that computes and animates the orbit of pluto, and have begun rewriting it using classes because this seems like a sensible way of introducing more planets into the simulation. i.e have a class that defines the physics, and then feed in specific planet data to get the orbital data.
    class Planet(object):
        m_sun = 1.989*(10**30)
        G = 6.67*(10**-11)
        dt = 1
        coords = []
        def __init__(self, x, y, vx, vy, m):
            self.x = x
            self.y = y
            self.vx = vx
            self.vy = vy
            self.m = m

        def genData(self):
            while self.dt < 100000000:
                r = ((self.x)**2 + (self.y)**2)**0.5
                a = ((self.G*self.m_sun)/r**2)
                ax = -a*((self.x)/r)
                ay = -a*((self.y)/r)
                self.vx = self.vx + ax*self.dt
                self.vy = self.vy + ay*self.dt
                self.x = self.x + self.vx*self.dt
                self.y = self.y + self.vy*self.dt
                coord = (self.x, self.y)
                print coord
                self.coords.append(coord)
                self.dt = self.dt + 1000

pluto = Planet(4495978707000, 0, 0, 4670, 1.305*(10**22))
pluto.genData()

I'm sure it isn't perfect, but it appears to be working (this is the first class i've built on my own). My question is how do I extract the data from 'coords' into a list that I can work with outside of the class.
I want to generate data for each planet, and then use this data to create an animation in Pygame. For example, a list of (x,y) coordinates for pluto, earth, saturn etc. As it stands, it churns out the data, but it doesn't appear to be accessible from outside the class.
I hope my question makes sense.
Thanks!

A: Your question's been answered, but I have some info you should find useful to improve your program. Technically, this info belongs in a comment (since you didn't actually ask about this in your question), but it wouldn't fit. :)

*

*Pluto's orbit is inclined quite a bit to the ecliptic, so if you want to plot it along with several other planets in the Solar System you need to work in 3D to be accurate. But I guess that's not a big deal for your application.

*Earth's orbit is tiny compared to Pluto, so you'll probably need to implement zooming to see them both on one animation.

*You can get more accuracy in your calculations by using the Standard gravitational parameter rather than using separate values of G and mass.

*Your algorithm for calculating velocity and position is called Euler integration. It's equivalent to approximating the curve of the orbit by a polygon. It works, but it's not very accurate. So you need to make the time delta very small otherwise the orbit won't be very realistic and it may not even be a closed curve. And even that doesn't help a lot because the error is accumulative, so eventually the computed orbit will bear little resemblance to reality.
No technique of numerical integration is perfect (except on very simple functions), but a popular family of integration techniques that are more accurate (and hence work ok with a much larger time step) are the Runge-Kutta methods. You can find lots of example code of orbit calculation using a Runge-Kutta method; most code examples use the variant known as RK4.
However, I strongly urge you to try Leapfrog integration. It's quite easy to code the synchronized form of Leapfrog and it has a major benefit over Runge-Kutta in that it's symplectic, which (roughly) means that it conserves energy, so the error won't accumulate from orbit to orbit.

A: Did you try pluto.coords?
You can access members of a class from outside by using the instance followed by dot followed by the member name, i.e. attribute access. This is just as you have done when calling the genData() method.
BTW, you can define your constants using exponential notation:
m_sun = 1.989e+30
G = 6.67e-11

and
pluto = Planet(4495978707000, 0, 0, 4670, 1.305e+22)

which is more readable (important) and saves a few calculations for the definition of your class (less/not important).

A: Instead of storing the values in self.coords, yield the values:
    def genData(self):
        while self.dt < 100000000:
            ...
            self.x = self.x + self.vx*self.dt
            self.y = self.y + self.vy*self.dt
            coord = (self.x, self.y)
            yield coord
            self.dt = self.dt + 1000

pluto = Planet(4495978707000, 0, 0, 4670, 1.305*(10**22))

for coord in pluto.genData():
    print(coord)

Note that this makes genData a generator function.
To obtain a list of coords, you can accumulate the values in the loop:
coords = []
for coord in pluto.genData():
    coords.append(coord)

or use coords = list(pluto.genData()).

By the way, it's usually a good policy to separate code-that-calculates from code-that-prints. That way you can call code-that-calculates many times, or include it in a chain of calculations without always emitting print statements.

I want to generate data for each planet, and then use this data to create an animation in Pygame.

It sounds like you don't need to accumulate the data. You can plot the current point for each planet without needing to know the planet's coordinate history. In that case, using generator functions would be more memory-efficient since they would allow you to generate the next coordinate for each planet without having to store all the coordinates in a list first:
# In Python2
import itertools as IT
for coords in IT.izip(*[planet.genData() for planet in [pluto, neptune, uranus, ...]]):
    # plot coords

or
# In Python3
for coords in zip(*[planet.genData() for planet in [pluto, neptune, uranus, ...]]):
    # plot coords

A: Actually it's very easy, just pluto.coords:
pluto = Planet(4495978707000, 0, 0, 4670, 1.305*(10**22))
pluto.genData()
print pluto.coords


text:
Q: Can you use a FileInterceptor with a TransformPipe I've met an issue with the TransformPipe - it works as long, as I don't use the FileInterceptor. Since I need both functionalities it confused me. I've created an issue on Github, but Kamil wrote on it, that it is a normal framework behavior. Nor I, nor my friends, didn't find any references to this "normal" behavior in the official documentation. Do you have any ideas?
Code is here:
Controller
@UsePipes(SamplePipe)
@UseInterceptors(FileInterceptor('file'))
@Post()
samplePost(@UploadedFile() file) {
  return file
}

Pipe
@Injectable()
export class SamplePipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    console.log("I'm working")
    return value;
  }
}

A: Pipes only work as the following types: 'body' | 'query' | 'param' | 'custom' corresponding to @Body(), @Query(), @Param() or custom decorators like @User(). In your example you don't have any of these and that's why the pipe is not applied.
So if you add one of these to your example, the pipe will be applied (in this case to @Body()).
@UsePipes(SamplePipe)
@UseInterceptors(FileInterceptor('file'))
@Post()
samplePost(@UploadedFile() file, @Body() body) {
                                 ^^^^^^^^^^^^^
  return file
}

If you use @UsePipes() the pipe will be applied everywhere where applicable. You can also use @Body(SimplePipe) body to only apply the pipe to the body.


text:
Q: What event can we use on select tag that triggers on change, but also on re-selecting the same option? I have been using v-on:change to trigger option changes in a vuejs app.
<select v-on:change="myMethod()">
  <option v-for="(val, key) in options" :value="val">
    {{key}}
  </option>
</select>

But I also need to trigger the method whenever the same option is re-selected a second time.
The change event is not triggered a second time in that case.
I cannot find lists of events for vuejs.
Here is one I found for HTML : https://www.w3schools.com/tags/ref_eventattributes.asp
I tried v-on:select, not doing anything
EDIT:
My intent is to link the option to different 2 values, one v-model would not suffice.
On second click, a boolean property of app.$data would be inversed. That's why I'm not using v-model.

A: This question actually has nothing to do with Vue, it's all about what native events <select> emits when an option is selected, change and input, and both of these events only fire when the selected option is changed and not when the selected option is re-selected.
As far as I know there is no way to detect when the same option is re-selected. You may need to roll your own control which has this feature.
You might be able to hack it by tracking mouse events, but it's likely that won't work 100% in every situation (different browsers and mobile, for example).

A: Do you want something like v-on:click or exactly this.

new Vue({
el:"#app",
data:{
  test:"",
  options:["11","22"]
},
methods:{
  myMethod:function(){
    if(this.test){
      console.log("myMethod called . test is :"+this.test+" at ->", new Date());
    }
  }
}
})

<select v-on:click="myMethod" v-model="test">
  <option v-for="(val, key) in options">
    {{val}}
  </option>
</select>

A: Try with onclick (on the select, not the options), it seems to work, not sure if it works on all browsers though, but it's being triggered when an option is clicked at least on webkit browsers.
https://jsfiddle.net/zdy25mo7/3/
html

Select a new car from the list.

<select id="mySelect">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

clicked: 0 times

javascript
var clicked = 1
document.getElementById('mySelect').onclick = function otherFunction(event) {
    document.getElementById("clicked_div").innerHTML = "clicked: " + clicked + " times";
    clicked++;
}


text:
Q: Querying cassandra error no viable alternative at input 'ALLOW' I'm trying to run a query on Cassandra through spark.
When running this command:
val test = sc.cassandraTable[Person](keyspace,table)
               .where("name=?","Jane").collect

I get the appropriate output for the query.
When I try to use the where statement to enter the query as a whole string I get an error.
I receive the query as a json:
{"clause": " name = 'Jane' "}

then turn it into a string.
When running
val query = (json \ "clause").get.as[String]
//turns json value into a string
val test = sc.cassandraTable[Person](keyspace,table)
                   .where(query).collect

I get the following error:
java.io.IOException: Exception during preparation of SELECT "uuid", "person", "age" FROM "test"."users" WHERE token("uuid") > ? AND token("uuid") <= ? AND  name = Jane    ALLOW FILTERING: line 1:232 no viable alternative at input 'ALLOW' (...<= ? AND  name = [Jane]    ALLOW...)
        at com.datastax.spark.connector.rdd.CassandraTableScanRDD.createStatement(CassandraTableScanRDD.scala:288)
        at com.datastax.spark.connector.rdd.CassandraTableScanRDD.com$datastax$spark$connector$rdd$CassandraTableScanRDD$$fetchTokenRange(CassandraTableScanRDD.scala:302)
        at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$18.apply(CassandraTableScanRDD.scala:328)
        at com.datastax.spark.connector.rdd.CassandraTableScanRDD$$anonfun$18.apply(CassandraTableScanRDD.scala:328)
        at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
        at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
        at com.datastax.spark.connector.util.CountingIterator.hasNext(CountingIterator.scala:12)
        at scala.collection.Iterator$class.foreach(Iterator.scala:893)
        at com.datastax.spark.connector.util.CountingIterator.foreach(CountingIterator.scala:4)
        at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)

I suspect that when I turn the json value " name = 'Jane' " into a string, I lose the single quotes hence I get " name = Jane " which of course raises an error. I tried escaping the single quotes with \ and with a second pair of single quotes around the name Jane {"clause": " name = ''Jane'' "}. It doesn't solve the issue.
Edit: After further testing it's definitely the json that loses the single quotes and CQL needs them to perform the query. Can anyone suggest a way to escape/save the presence of the single quotes? I tried escaping with \ double single quotes '' . Is there a way to use JSON to provide proper whole CQL statements?

A: Please use Unicode character \u0027.


text:
Q: TextMate GetBundle stopped working in Snow Leopard It seems that I am no longer able to Get Bundles using TextMate after upgrading to Snow Leopard.
I get the following error message. Googling shows no solutions. I have updated to the latest GetBundle via svn to no avail.
/Applications/TextMate.app/Contents/SharedSupport/Support/lib/osx/plist.bundle: dlopen(/Applications/TextMate.app/Contents/SharedSupport/Support/lib/osx/plist.bundle, 9): no suitable image found.  Did find: (LoadError)
    /Applications/TextMate.app/Contents/SharedSupport/Support/lib/osx/plist.bundle: no matching architecture in universal wrapper - /Applications/TextMate.app/Contents/SharedSupport/Support/lib/osx/plist.bundle
    from /Users/jauderho/Library/Application Support/TextMate/Bundles/GetBundles.tmbundle/Support/getBundles.rb:4

A: Did you try upgrading the GetBundle bundle itself? I thought they stopped using SVN, so you may be pulling from the wrong repository.
http://github.com/textmate/getbundle.tmbundle


text:
Q: Is it possible to design an automaton that accepts irrational number? Given a rational number, would it be possible to know whether the root or some other power of the number is an irrational number? Can an automaton be designed for such a purpose?

A: An irrational number is an infinite string, and if you want an automaton that can read it, it will need to continue reading infinitely.
You cannot build a decider (a machine that always halts with output true or false), but you can build an acceptor (a machine that halts with false, but continues forever for true), which is what I believe you're asking.
Consider a machine that accepts the irrational number of the form
0.10110111011110111110...

Where the lengths of runs of 1s is always growing between 0s. It's relatively easy to define a Turing machine that can accept this number.
(For the implementation for such a machine, I'd suggest The Annotated Turing, which also has an implementation for a machine that accepts √2.)


text:
Q: telnet on port 1433 not working
telnet some_ip 1433

On Windows 7 this line doesn't work. It says it cannot establish connection. I'm 100% percent sure that the server has this port open. For a friend of mine this line works.
I suspect 2 reasons:

*

*My ISP blocks this port.

*My system blocks it.

I turned off the firewall and windows firewall. Is there anything else I can do to make sure the problem is not related to my system configuration?
BTW, I don't know if it's important, but

telnet some_ip 80

works fine
EDIT
Wireshark log here
I replaced the ip I tried to telnet with
<my_ip>

A: Using telnet is a very good and useful tool to trace/troubleshoot connectivity.
Here is what I do:
a) On the SQL Server box itself: telnet localhost 1433
-- This is to make sure a remote connection is even possible
b) On another box, on the same local net where the SQL server box lives: telnet  1433
-- This tells you if it is even possible to hit the port "off the box"
c) Now, if everything is working... it depends on what tools and access you have.
Ex 1: Can the telnet be done from the firewall where the SQL Server lives?
Ex 2: Can telnet be done from another non-local-to-SQL system that has to go through that firewall?
Often you can only get through 'b', and then you have to look at three things step by step:

*

*Firewall where SQL Server lives

*Firewall hardware on your side (where you run telnet)

*Local OS firewall on the machine you are at running telnet (e.g. outbound filter or such blocking your outbound connection)

A: On the PC, run a traffic sniffer like Wireshark or Network Monitor and see what the network responses are when you try to open a telnet connection. That will tell you if outbound traffic on that port is being blackholed or otherwise tampered with.
It is highly unlikely that an ISP would be blocking port 1433 or application layer traffic that bares the marks of Telnet. Try another PC or device on the same LAN, like a smart phone, to narrow the possibilities down.

A: I spent two days to troubleshoot the same problem: telnet to port 1433 failed. After grabbing a lot of hairs, finally I found the problem!
The problem is that the server Internet connection is identified as "Public network", while it should be a domain network.
After restart the NLA service(refer to Domain Controller thinks its on a Public Network), the network is identified as domain network again, and then the problem is gone. My firewall setting is set to "Domain" profile, when it is a public network, the firewall setting does not work.
I hope this information will be helpful for someone else.

A: just to be sure what does the following query returns
declare @dir nvarchar(4000)

exec master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'SOFTWARE\Microsoft\MSSQLServer\SuperSocketNetLib\Tcp\IPAll',
    N'TcpDynamicPorts',
    @dir output

select @dir

or, after editing your instance name
declare @dir nvarchar(4000)

exec master.dbo.xp_regread
    N'HKEY_LOCAL_MACHINE',
    N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL11.SQL110EXP02\MSSQLServer\SuperSocketNetLib\Tcp\IPAll',
    N'TcpDynamicPorts',
    @dir output

select @dir


text:
Q: In Python, is it possible to get the environment variables out of a Popen child process? I am calling two shell scripts in a row. I'd like to get the environment variables at the end of the first one so that I can inject them into the second one as it starts.
I'm fairly sure this isn't possible, but I'd just like to make sure.


text:
Q: How to create/append the Application folder name at the end of the Target/installation path I want to create/append the Application folder name at the end of the Target/installation path.
The default path is "C:\CompanyName\"
In this case also it should install in "C:\CompanyName\AppName"
And if the user changes the path to "C:\Test\" (by browse dialog or by typing in the text box), then installation should happen in the "C:\Test\AppName"
I've referred the Wix UI as "WixUI_InstallDir"
I've also Set the Property Id="WIXUI_INSTALLDIR" Value="APPPATH".
And my all shortcuts should point to the final installation path.
Sample snippet code:
Product.wxs
<?xml version='1.0' encoding='windows-1252'?>
 <Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
    <!--- some code here --->
    <Property Id="APPPATH" Secure="yes"><![CDATA[C:\CompanyName]]></Property>
    <Property Id="WIXUI_INSTALLDIR" Value="APPPATH" />
    <Property Id="ALLUSERS">1</Property>

<!--- some code here --->
    <Directory Id='TARGETDIR' Name='SourceDir'>
        <Directory Id='ProgramFilesFolder' Name='PFiles'>
            <Directory Id='APPPATH' Name='Product_Title'>
                  <Directory Id='ConfigurationId' Name='Configuration'>
            <!--- some code here --->
                    </Directory>
                 </Directory>
            </Directory>
        </Directory>

        <!--- some code here --->
     <UI Id="CustomWixUI_Mondo">
              <UIRef Id= "AppWixUI_InstallDir" />
              <UIRef Id="WixUI_ErrorProgressText" />
    </UI>

</Product>

AppWixUI_InstallDir.wxs
<?xml version="1.0" encoding="UTF-8"?>
 <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Fragment>
    <UI Id="AppWixUI_InstallDir">

        <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
        <Property Id="WixUI_Mode" Value="InstallDir" />

        <DialogRef Id="BrowseDlg" />
        <!-- some more code... .... -->

        <Publish Dialog="BrowseDlg" Control="OK" Event="DoAction" Value="WixUIValidatePath" Order="3">1</Publish>
        <Publish Dialog="BrowseDlg" Control="OK" Event="SpawnDialog" Value="InvalidDirDlg" Order="4"><![CDATA[WIXUI_INSTALLDIR_VALID<>"1"]]></Publish>

        <Publish Dialog="AppInstallDirDlg" Control="InstallNoShield" Event="SetTargetPath" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish>
        <Publish Dialog="AppInstallDirDlg" Control="InstallNoShield" Event="DoAction" Value="WixUIValidatePath" Order="2">NOT WIXUI_DONTVALIDATEPATH</Publish>
        <Publish Dialog="AppInstallDirDlg" Control="InstallNoShield" Event="SpawnDialog" Value="InvalidDirDlg" Order="3"><![CDATA[NOT WIXUI_DONTVALIDATEPATH AND WIXUI_INSTALLDIR_VALID<>"1"]]></Publish>
        <Publish Dialog="AppInstallDirDlg" Control="ChangeFolder" Property="_BrowseProperty" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish>
        <Publish Dialog="AppInstallDirDlg" Control="ChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish>

        <!-- some more code... .... -->

    </UI>

    <UIRef Id="WixUI_Common" />
 </Fragment>

AppInstallDirDlg.wxs
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
 <Fragment>
    <UI>
        <Dialog Id="AppInstallDirDlg" Width="370" NoMinimize = "yes" Height="270" Title="InstallDirDlg_Title">

            <Control Id="InstallNoShield" Type="PushButton" ToolTip="Next" ElevationShield="no" X="4" Y="243" Width="80" Height="17" Default="yes" Hidden="yes" Disabled="yes" Text="Next">
                <Condition Action="show">NOT Installed </Condition>
                <Condition Action="enable">NOT Installed</Condition>
                <Condition Action="default">NOT Installed</Condition>
                <Publish Event="EndDialog" Value="Return"><![CDATA[OutOfDiskSpace <> 1]]></Publish>
                <Publish Event="SpawnDialog" Value="OutOfRbDiskDlg">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)</Publish>
                <Publish Event="EndDialog" Value="Return">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish>
                <Publish Event="EnableRollback" Value="False">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish>
                <Publish Event="SpawnDialog" Value="OutOfDiskDlg">(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")</Publish>
            </Control>

            <!-- <Control Id="Next" Type="PushButton" X="4" Y="243" Width="56" Height="17" ToolTip="Next" Default="yes" Text="Next" /> -->
            <Control Id="Back" Type="PushButton" X="246" Y="243" Width="56" Height="17" ToolTip="Back" Text="Back" >
                <Publish Event="NewDialog" Value="AppLicenseAgreementDlg">1</Publish>
            </Control>
            <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" ToolTip="Cancel" Cancel="yes" Text="Cancel">
                <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
            </Control>

            <Control Id="FolderLabel" Type="Text" X="20" Y="58" Width="290" Height="15" NoPrefix="yes" Text="InstallDirDlgFolderLabel" />
            <Control Id="Folder" Type="PathEdit" X="20" Y="75" Width="320" Height="18" Property="WIXUI_INSTALLDIR" Indirect="yes" />
            <Control Id="ChangeFolder" Type="PushButton" X="20" Y="96" Width="80" Height="17" ToolTip="Change Folder" Text="InstallDirDlgChange" />
            <Control Id="DiskUsage" Type="Text" X="20" Y="128" Width="290" Height="15" NoPrefix="yes" Text="InstallDirDlgDiskUsage" />
            <Control Id="VolumeList" Type="VolumeCostList" X="20" Y="145" Width="320" Height="75" Sunken="yes" Fixed="yes" Remote="yes" Text="DiskCostDlgVolumeList" />
        </Dialog>
      </UI>
   </Fragment>
</Wix>

Any help please...

A: If you don't need to show the folder MyApp in the dialogs, you can do the following:
<Directory Id="TARGETDIR" Name="SourceDir">
    <Directory Id="INSTALLFOLDER" Name="CompanyName">
        <Directory Id="MyApp" Name="MyApp" />
    </Directory>
</Directory>

And in your components replace INSTALLFOLDER with MyApp, this way:
<Component Id="Component_Core" Guid="*" Directory="MyApp">

As a side note, I don't recommend messing up with the dialogs just to show something like "C:\CompanyName\MyApp" or "C:\Temp\MyApp". It is easier if you just show "C:\CompanyName" or "C:\Temp" and install the files to the MyApp folder.
If you still want to show the full text, try something like this (not recommended):
<Property Id="INDIRECT_FOLDER" Value="MyApp" />

<Dialog Id="NewInstallDirDlg" Width="370" Height="270" Title="!(loc.InstallDirDlg_Title)">
    <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)" />
    <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" />
    <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)">
        <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
    </Control>

    <Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes" Text="!(loc.InstallDirDlgDescription)" />
    <Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="!(loc.InstallDirDlgTitle)" />
    <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" />
    <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
    <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />

    <Control Id="FolderLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" Text="!(loc.InstallDirDlgFolderLabel)" />
    <Control Id="Folder" Type="PathEdit" X="20" Y="100" Width="320" Height="18" Property="INDIRECT_FOLDER" Indirect="yes" />
    <Control Id="ChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />
</Dialog>