Programs & Examples On #Active directory

Active Directory (AD) is a distributed directory service created by Microsoft. It stores all information and settings for a deployment in a central database. AD allows administrators to assign policies, deploy and update software. AD networks can vary from a small installation with a few computers, users and printers to tens of thousands of users, many different network domains and large server farms spanning many geographical sites.

Authenticating in PHP using LDAP through Active Directory

For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.

I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.

"A referral was returned from the server" exception when accessing AD from C#

This is the answer for the question.Reason for the cause is my LDAP string was wrong.

    try
    {
        string adServer = ConfigurationManager.AppSettings["Server"];
        string adDomain = ConfigurationManager.AppSettings["Domain"];
        string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
        string password = ConfigurationManager.AppSettings["Password"];
        string[] dc = adDomain.Split('.');
        string dcAdDomain = string.Empty;

        foreach (string item in dc)
        {
            if (dc[dc.Length - 1].Equals(item))
                dcAdDomain = dcAdDomain + "DC=" + item;
            else
                dcAdDomain = dcAdDomain + "DC=" + item + ",";
        }

        DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);

        DirectorySearcher ds = new DirectorySearcher(de);

        ds.SearchScope = SearchScope.Subtree;

        ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

        if (ds.FindOne() != null)
            return true;
    }
    catch (Exception ex)
    {
        ExLog(ex);
    }
    return false;

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

This is not a reply (I cant post comments), just few random ideas might be helpful. Unfortunately I've never dealt with citrix, only with regular windows servers.

_0. Ensure you're not a victim of Windows Firewall, or any other personal firewall that selectively blocks processes.

Add 10 minutes Sleep() to the first line of your .NET app, then run both VBScript file and your stand-alone application, run sysinternals process explorer, and compare 2 processes.

_1. Same tab, "command line" and "current directory". Make sure they are the same.

_2. "Environment" tab. Make sure they are the same. Normally child processes inherit the environment, but this behaviour can be easily altered.

The following check is required if by "run my script" you mean anything else then double-clicking the .VBS file:

_3. Image tab, "User". If they differ - it may mean user has no access to the network (like localsystem), or user token restricted to delegation and thus can only access local resources (like in the case of IIS NTLM auth), or user has no access to some local files it wants.

What are the differences between LDAP and Active Directory?

https://jumpcloud.com/blog/difference-between-ldap-and-active-directory/

Realistically, there are probably more differences than similarities between the two directory solutions. Microsoft’s AD is largely a directory for Windows users, devices, and applications. AD requires a Microsoft Domain Controller to be present and when it is, users are able to single sign-on to Windows resources that live within the domain structure.

LDAP, on the other hand, has largely worked outside of the Windows structure focusing on the Linux / Unix environment and with more technical applications. LDAP doesn’t have the same concepts of domains or single sign-on. LDAP is largely implemented with open source solutions and as a result has more flexibility than AD.

Another critical difference between LDAP and Active Directory is how AD and LDAP each approach device management. AD manages Windows devices through and Group Policy Objects (GPOs). A similar concept doesn’t exist within LDAP. Both LDAP and AD are highly different solutions and as a result many organization must leverage both to serve different purposes.

This is why there’s an obvious opportunity for innovation. Why leverage and manage two complete systems, when one system can effectively merge the two?

Adding and removing extensionattribute to AD object

I used the following today - It works!

Add a value to an extensionAttribute

 $ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
    Set-ADUser –Identity $ThisUser -add @{"extensionattribute1"="MyString"}

Remove a value from an extensionAttribute

  $ThisUser = Get-ADUser -Identity $User -Properties extensionAttribute1
  Set-ADUser –Identity $ThisUser -Clear "extensionattribute1" 

How to get all the AD groups for a particular user?

I would like to say that Microsoft LDAP has some special ways to search recursively for all of memberships of a user.

  1. The Matching Rule you can specify for the "member" attribute. In particular, using the Microsoft Exclusive LDAP_MATCHING_RULE_IN_CHAIN rule for "member" attribute allows recursive/nested membership searching. The rule is used when you add it after the member attribute. Ex. (member:1.2.840.113556.1.4.1941:= XXXXX )

  2. For the same Domain as the Account, The filter can use <SID=S-1-5-21-XXXXXXXXXXXXXXXXXXXXXXX> instead of an Accounts DistinguishedName attribute which is very handy to use cross domain if needed. HOWEVER it appears you need to use the ForeignSecurityPrincipal <GUID=YYYY> as it will not resolve your SID as it appears the <SID=> tag does not consider ForeignSecurityPrincipal object type. You can use the ForeignSecurityPrincipal DistinguishedName as well.

Using this knowledge, you can LDAP query those hard to get memberships, such as the "Domain Local" groups an Account is a member of but unless you looked at the members of the group, you wouldn't know if user was a member.

//Get Direct+Indirect Memberships of User (where SID is XXXXXX)

string str = "(& (objectCategory=group)(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//Get Direct+Indirect **Domain Local** Memberships of User (where SID is XXXXXX)

string str2 = "(& (objectCategory=group)(|(groupType=-2147483644)(groupType=4))(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//TAA DAA



Feel free to try these LDAP queries after substituting the SID of a user you want to retrieve all group memberships of. I figure this is similiar if not the same query as what the PowerShell Command Get-ADPrincipalGroupMembership uses behind the scenes. The command states "If you want to search for local groups in another domain, use the ResourceContextServer parameter to specify the alternate server in the other domain."

If you are familiar enough with C# and Active Directory, you should know how to perform an LDAP search using the LDAP queries provided.

Additional Documentation:

"Active Directory Users and Computers" MMC snap-in for Windows 7?

As "me1" has mentioned you can do this assuming that your version of Windows 7 is either Professional or Ultimate, the PC is on the domain and you have preinstall the Remote Server Administration Tools (Windows6.1-KB958830-x64-RefreshPkg.msu or newer) then you'll be able to do the following:

Step 1. Select "Start", select "Control Panel", select "Programs" and click on "Turn Windows features on or off".

Step 2. Check the following 5 features:

"remote server administration tools>feature administration tools>group policy management tools"

"remote server administration tools>feature administration tools>smtp server tools"

"remote server administration tools>role administration tools>ad ds and ad lds tools>active directory module for windows powershell"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>active directory administrative center"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>ad ds snap-ins and command-line tools"

Step 3. Click "OK".

Active Directory LDAP Query by sAMAccountName and Domain

"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.

So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.

Once you bound successfully, your query in it's current shape is all you need.

BTW: Choosing "ObjectCategory=Person" over "ObjectClass=user" was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

How to get all groups that a user is a member of?

Putting this here for future reference. I'm in the midst of an email migration. I need to know each user account and its respective group membership, and also I need to know each group and its respective members.

I'm using the code block below to output a CSV for each user's group membership.

Get-ADUser -Filter * |`
  ForEach-Object { `
    $FileName = $_.SamAccountName + ".csv" ; `
    $FileName ; `
    Get-ADPrincipalGroupMembership $_ | `
      Select-Object -Property SamAccountName, name, GroupScope, GroupCategory | `
        Sort-Object -Property SamAccountName | `
          Export-Csv -Path $FileName -Encoding ASCII ; `
  }

The export process for the groups and their respective members was a little convoluted, but the below works. The output filenames include the type of group. Therefore, the email distribution groups I need are/should be the Universal and Global Distribution groups. I should be able to just delete or move the resulting TXT files I don't need.

Get-ADGroup -Filter * | `
 Select-Object -Property Name, DistinguishedName, GroupScope, GroupCategory | `
  Sort-Object -Property GroupScope, GroupCategory, Name | `
   Export-Csv -Path ADGroupsNew.csv -Encoding ASCII

$MyCSV = Import-Csv -Path .\ADGroupsNew.csv -Encoding ASCII

$MyCSV | `
 ForEach-Object { `
  $FN = $_.GroupScope + ", " + $_.GroupCategory + ", " + $_.Name + ".txt" ; `
  $FN ; `
  Get-ADGroupMember -Identity $_.DistinguishedName | `
   Out-File -FilePath $FN -Encoding ASCII ; $FN=""; `
  }

What are CN, OU, DC in an LDAP search?

I want to add somethings different from definitions of words. Most of them will be visual.

Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service

Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).the Data (Information) Model

To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).

enter image description here

If you want to get more depth information, you visit here

Converting LastLogon to DateTime format

Get-ADUser -Filter {Enabled -eq $true} -Properties Name,Manager,LastLogon | 
Select-Object Name,Manager,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

Even better use implicit remoting to use a module from another Machine!

$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM

This will allow you to use the module off a remote PC for as long as the PSSession is connected.

More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx

How to get the groups of a user in Active Directory? (c#, asp.net)

In case Translate works locally but not remotly e.i group.Translate(typeof(NTAccount)

If you want to have the application code executes using the LOGGED IN USER identity, then enable impersonation. Impersonation can be enabled thru IIS or by adding the following element in the web.config.

<system.web>
<identity impersonate="true"/>

If impersonation is enabled, the application executes using the permissions found in your user account. So if the logged in user has access, to a specific network resource, only then will he be able to access that resource thru the application.

Thank PRAGIM tech for this information from his diligent video

Windows authentication in asp.net Part 87:

https://www.youtube.com/watch?v=zftmaZ3ySMc

But impersonation creates a lot of overhead on the server

The best solution to allow users of certain network groups is to deny anonymous in the web config <authorization><deny users="?"/><authentication mode="Windows"/>

and in your code behind, preferably in the global.asax, use the HttpContext.Current.User.IsInRole :

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If

NOTE: The Group must be written with a backslash \ i.e. "TheDomain\TheGroup"

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

You can check that with:

$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )

Domain Account keeping locking out with correct password every few minutes

May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.

LDAP root query syntax to search more than one specific OU

It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL

Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.

Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

How to get the current user's Active Directory details in C#

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}

[email protected] is the UserPrincipalName, but it isn't a required field.

How can I get a list of users from active directory?

Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.

Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.

using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
    List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
    foreach(var u in users)
        {
            DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
            Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
        }
}

Validate a username and password against Active Directory?

Here my complete authentication solution for your reference.

First, add the following four references

 using System.DirectoryServices;
 using System.DirectoryServices.Protocols;
 using System.DirectoryServices.AccountManagement;
 using System.Net; 

private void AuthUser() { 


      try{
            string Uid = "USER_NAME";
            string Pass = "PASSWORD";
            if (Uid == "")
            {
                MessageBox.Show("Username cannot be null");
            }
            else if (Pass == "")
            {
                MessageBox.Show("Password cannot be null");
            }
            else
            {
                LdapConnection connection = new LdapConnection("YOUR DOMAIN");
                NetworkCredential credential = new NetworkCredential(Uid, Pass);
                connection.Credential = credential;
                connection.Bind();

                // after authenticate Loading user details to data table
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Uid);
                DirectoryEntry up_User = (DirectoryEntry)user.GetUnderlyingObject();
                DirectorySearcher deSearch = new DirectorySearcher(up_User);
                SearchResultCollection results = deSearch.FindAll();
                ResultPropertyCollection rpc = results[0].Properties;
                DataTable dt = new DataTable();
                DataRow toInsert = dt.NewRow();
                dt.Rows.InsertAt(toInsert, 0);

                foreach (string rp in rpc.PropertyNames)
                {
                    if (rpc[rp][0].ToString() != "System.Byte[]")
                    {
                        dt.Columns.Add(rp.ToString(), typeof(System.String));

                        foreach (DataRow row in dt.Rows)
                        {
                            row[rp.ToString()] = rpc[rp][0].ToString();
                        }

                    }  
                }
             //You can load data to grid view and see for reference only
                 dataGridView1.DataSource = dt;


            }
        } //Error Handling part
        catch (LdapException lexc)
        {
            String error = lexc.ServerErrorMessage;
            string pp = error.Substring(76, 4);
            string ppp = pp.Trim();

            if ("52e" == ppp)
            {
                MessageBox.Show("Invalid Username or password, contact ADA Team");
            }
            if ("775?" == ppp)
            {
                MessageBox.Show("User account locked, contact ADA Team");
            }
            if ("525?" == ppp)
            {
                MessageBox.Show("User not found, contact ADA Team");
            }
            if ("530" == ppp)
            {
                MessageBox.Show("Not permitted to logon at this time, contact ADA Team");
            }
            if ("531" == ppp)
            {
                MessageBox.Show("Not permitted to logon at this workstation, contact ADA Team");
            }
            if ("532" == ppp)
            {
                MessageBox.Show("Password expired, contact ADA Team");
            }
            if ("533?" == ppp)
            {
                MessageBox.Show("Account disabled, contact ADA Team");
            }
            if ("533?" == ppp)
            {
                MessageBox.Show("Account disabled, contact ADA Team");
            }



        } //common error handling
        catch (Exception exc)
        {
            MessageBox.Show("Invalid Username or password, contact ADA Team");

        }

        finally {
            tbUID.Text = "";
            tbPass.Text = "";

        }
    }

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

Authenticating against Active Directory with Java on Linux

As ioplex and others have said, there are many options. To authenticate using LDAP (and the Novell LDAP API), I have used something like:


LDAPConnection connection = new LDAPConnection( new LDAPJSSEStartTLSFactory() );
connection.connect(hostname, port);
connection.startTLS();
connection.bind(LDAPConnection.LDAP_V3, username+"@"+domain, password.getBytes());

As a "special feature", Active Directory allows LDAP binds against "user@domain" without using the distinguished name of the account. This code uses StartTLS to enable TLS encryption on the connection; the other alternative is LDAP over SSL, which is not supported by my AD servers.

The real trick is in locating the server and host; the official way is to use a DNS SRV (service) record lookup to locate a bundle of candidate hosts, then do a UDP-based LDAP "ping" (in a particular Microsoft format) to locate the correct server. If you are interested, I've posted some blog articles about my journey of adventure and discovery in that area.

If you want to do Kerberos-based username/password authentication, you are looking at another kettle of fish; it is doable with the Java GSS-API code, although I am not sure it performs the final step to validate the authentication. (The code doing the validation can contact the AD server to check the username and password, which results in a ticket granting ticket for the user, but to ensure the AD server is not being impersonated, it also needs to try to get a ticket for the user to itself, which is somewhat more complicated.)

If you want to do Kerberos-based single sign-on, assuming your users are authenticated to the domain, you can do that as well with the Java GSS-API code. I would post a code sample, but I still need to turn my hideous prototype into something fit for human eyes. Check out some code from SpringSource for some inspiration.

If you are looking for NTLM (which I was given to understand is less secure) or something else, well, good luck.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How to Export-CSV of Active Directory Objects?

From a Windows Server OS execute the following command for a dump of the entire Active Director:

csvde -f test.csv

This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:

csvde -f test.csv -r objectClass=user 

You can further restrict the command to give you only the fields you need relevant to the search requested such as:

csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf

If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Get user's non-truncated Active Directory groups from command line

A little stale post, but I figured what the heck. Does "whoami" meet your needs?

I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.

whoami /groups

Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.

Group names only:

whoami /groups /fo list |findstr /c:"Group Name:"

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

Finding CN of users in Active Directory

You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.

alt text

Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement namespace, you could also do it programmatically:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.

Or:

UserPrincipal myself = UserPrincipal.Current;

This will give you a UserPrincipal object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!

How to switch to another domain and get-aduser

best solution TNX to Drew Chapin and all of you too:

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

my script:

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
 Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

Error 0x80005000 and DirectoryServices

Spent a day on my similar issue, but all these answers didn't help.

Turned out in my case, I didn't enable Windows Authentication in IIS setting...

Query to list all users of a certain group

If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

Quick way to retrieve user information Active Directory

Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.

DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");

if (deUser != null)
{
  ... do something with your user
}

And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:

// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");

// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");

There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.

Gradle proxy configuration

For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:

systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl 
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD

Where : proxyUrl is the url of the proxy server (http://.....)

proxyPort is the port (usually 8080)

USER is my domain user

PASSWORD, my password

In this case, the proxy for http and https is the same

Git credential helper - update password

For Windows 10 it is:

Control Panel > User Accounts > Manage your Credentials > Windows Credentials, search for the git credentials and edit

What's wrong with overridable method calls in constructors?

I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :

public abstract class BasicPage extends WebPage {

    public BasicPage() {
    }

    @Override
    public void onInitialize() {
        add(new Label("title", getTitle()));
    }

    protected abstract String getTitle();
}

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

What does '?' do in C++?

This is a ternary operator, it's basically an inline if statement

x ? y : z

works like

if(x) y else z

except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.

It's useful for writing succinct code, but can be overused to create hard to maintain code.

How to create an AVD for Android 4.0

I just did the same. If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages. One of these is named "ARM EABI v7a System Image".

This is what you need to download in order to create an Android 4.0 virtual device:

The Android SDK download system

Creating random colour in Java?

If you want pleasing, pastel colors, it is best to use the HLS system.

final float hue = random.nextFloat();
// Saturation between 0.1 and 0.3
final float saturation = (random.nextInt(2000) + 1000) / 10000f;
final float luminance = 0.9f;
final Color color = Color.getHSBColor(hue, saturation, luminance);

Cannot open local file - Chrome: Not allowed to load local resource

There is a workaround using Web Server for Chrome.
Here are the steps:

  1. Add the Extension to chrome.
  2. Choose the folder (C:\images) and launch the server on your desired port.

Now easily access your local file:

function run(){
   // 8887 is the port number you have launched your serve
   var URL = "http://127.0.0.1:8887/002.jpg";

   window.open(URL, null);

}
run();

PS: You might need to select the CORS Header option from advanced setting incase you face any cross origin access error.

How to get full file path from file name?

private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

Django check for any exists for a query

this worked for me!

if some_queryset.objects.all().exists(): print("this table is not empty")

Join two data frames, select all columns from one and some columns from the other

Not sure if the most efficient way, but this worked for me:

from pyspark.sql.functions import col

df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

The trick is in:

[col('a.'+xx) for xx in a.columns] : all columns in a

[col('b.other1'),col('b.other2')] : some columns of b

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

First - I have to direct you to http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html -- she does an amazing job.

The basic idea is that you use

<T extends SomeClass>

when the actual parameter can be SomeClass or any subtype of it.

In your example,

Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));

You're saying that expected can contain Class objects that represent any class that implements Serializable. Your result map says it can only hold Date class objects.

When you pass in result, you're setting T to exactly Map of String to Date class objects, which doesn't match Map of String to anything that's Serializable.

One thing to check -- are you sure you want Class<Date> and not Date? A map of String to Class<Date> doesn't sound terribly useful in general (all it can hold is Date.class as values rather than instances of Date)

As for genericizing assertThat, the idea is that the method can ensure that a Matcher that fits the result type is passed in.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.

Use insted of:

dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}); 
string jsonstring = JsonConvert.SerializeObject(result);

something like that:

string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();

Then you can use DeserializeObject method:

var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);

Hope this helps.

Get selected value/text from Select on change

Use

document.getElementById("select_id").selectedIndex

Or to get the value:

document.getElementById("select_id").value

How to Change Margin of TextView

TextView does not support setMargins. Android docs say:

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

Range with step of type float

One explanation might be floating point rounding issues. For example, if you could call

range(0, 0.4, 0.1)

you might expect an output of

[0, 0.1, 0.2, 0.3]

but you in fact get something like

[0, 0.1, 0.2000000001, 0.3000000001]

due to rounding issues. And since range is often used to generate indices of some sort, it's integers only.

Still, if you want a range generator for floats, you can just roll your own.

def xfrange(start, stop, step):
    i = 0
    while start + i * step < stop:
        yield start + i * step
        i += 1

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);
}

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

How to add a button dynamically using jquery

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

Demo: Plunker

Android button with icon and text

For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) on the buttons object will assist.

Sample

Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);

Find an item in List by LINQ?

This will help you in getting the first or default value in your Linq List search

var results = _List.Where(item => item == search).FirstOrDefault();

This search will find the first or default value it will return.

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

Simple regular expression for a decimal with a precision of 2

Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

Amazon S3 exception: "The specified key does not exist"

For me, the object definitely existed and was uploaded correctly, however, its s3 url still threw the same error:

<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>

I found out that the reason was because my filename contained a # symbol, and I guess certain characters or symbols will also cause this error.

Removing this character and generating the new s3 url resolved my issue.

CSS Classes & SubClasses

Just put a space between .area1 and .item, e.g:

.area1 .item
{
    color:red;
}

this style applies to elements with class item inside an element with class area1.

Return list using select new in LINQ

public List<Object> GetProjectForCombo()
{
   using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
   {
     var query = db.Project
     .Select<IEnumerable<something>,ProjectInfo>(p=>
                 return new ProjectInfo{Name=p.ProjectName, Id=p.ProjectId);       

     return query.ToList<Object>();
   }

}

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

Maven: Failed to retrieve plugin descriptor error

I had the same issue in Windows

and it worked since my proxy configuration in settings.xml file was changed

So locate and edit the file inside the \conf folder, for example : C:\Program Files\apache-maven-3.2.5\conf

<proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>jorgesys</username>
      <password>supercalifragilisticoespialidoso</password>
      <host>proxyjorgesys</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
  • In my case i had to chage from port 80 to 8080
  • If you can´t edit this file that is located inside /program files you can make a copy, edit the file and replace the file located into /program files folder.

How to select all elements with a particular ID in jQuery?

I would use Different IDs but assign each DIV the same class.

<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>

This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length


Ok what about adding multiple classes to each countdown timer. IE:

<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>

That way you get the best of both worlds. It even allows repeat 'IDS'

Clearing Magento Log Data

You may check good article here:

http://blog.magalter.com/magento-database-size

It has instructions how to check database size, truncate some tables and how to configure automatic table cleaning.

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

Python/BeautifulSoup - how to remove all tags from an element?

With BeautifulStoneSoup gone in bs4, it's even simpler in Python3

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
text = soup.get_text()
print(text)

Passing additional variables from command line to make

If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards

example :

make unittest=*

I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run

Checking if a double (or float) is NaN in C++

You can use the isnan() function, but you need to include the C math library.

#include <cmath>

As this function is part of C99, it is not available everywhere. If your vendor does not supply the function, you can also define your own variant for compatibility.

inline bool isnan(double x) {
    return x != x;
}

Best C/C++ Network Library

Aggregated List of Libraries

How to play video with AVPlayerViewController (AVKit) in Swift

a bug(?!) in iOS10/Swift3/Xcode 8?

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
    let playerItem = AVPlayerItem(url: url)
    let player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300)
    self.view.layer.addSublayer(playerLayer)
}

does not work (empty rect...)

this works:

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){

            let player = AVPlayer(url: url)
            let controller=AVPlayerViewController()
            controller.player=player
            controller.view.frame = self.view.frame
            self.view.addSubview(controller.view)
            self.addChildViewController(controller)
            player.play()
        }

Same URL...

Storing WPF Image Resources

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

Detecting EOF in C

as a starting point you could try replacing

while(!EOF)

with

while(!feof(stdin))

How to find and replace all occurrences of a string recursively in a directory tree?

Try this:

find /home/user/ -type f | xargs sed -i  's/a\.example\.com/b.example.com/g'

In case you want to ignore dot directories

find . \( ! -regex '.*/\..*' \) -type f | xargs sed -i 's/a\.example\.com/b.example.com/g'

Edit: escaped dots in search expression

CSS disable hover effect

I have really simple solution for this.

just create a new class

.noHover{
    pointer-events: none;
}

and use this to disable any event on it. use it like:

<a href='' class='btn noHover'>You cant touch ME :P</a>

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

How to Set Focus on Input Field using JQuery

If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  

Send value of submit button when form gets posted

To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.

At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().

Buy anyway , user4035 just beat me to it , his code will "fix" this for you.

django MultiValueDictKeyError error, how do I deal with it

You get that because you're trying to get a key from a dictionary when it's not there. You need to test if it is in there first.

try:

is_private = 'is_private' in request.POST

or

is_private = 'is_private' in request.POST and request.POST['is_private']

depending on the values you're using.

Fatal error: Call to undefined function mysql_connect()

Check if mysqli module is installed for your PHP version

$ ls /etc/php/7.0/mods-available/mysql*
/etc/php/7.0/mods-available/mysqli.ini /etc/php/7.0/mods-available/mysqlnd.ini

Enable the module

$ sudo phpenmod mysqli

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

Alternatively, you can apply maven-compiler-plugin with appropriate java version by adding this to your pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Eclipse plugin for generating a class diagram

Try eUML2. its a single click generator no need to drag n drop.

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

is the + operator less performant than StringBuffer.append()

I like to use functional style, such as:

function href(url,txt) {
  return "<a href='" +url+ "'>" +txt+ "</a>"
}

function li(txt) {
  return "<li>" +txt+ "</li>"
}

function ul(arr) {
  return "<ul>" + arr.map(li).join("") + "</ul>"
}

document.write(
  ul(
    [
      href("http://url1","link1"),
      href("http://url2","link2"),
      href("http://url3","link3")
    ]
  )
)

This style looks readable and transparent. It leads to the creation of utilities which reduces repetition in code.

This also tends to use intermediate strings automatically.

Target class controller does not exist - Laravel 8

In Laravel 8 the way routes are specified has changed:

Route::resource('homes', HomeController::class)->names('home.index');

Generate a dummy-variable

I use such a function (for data.table):

# Ta funkcja dla obiektu data.table i zmiennej var.name typu factor tworzy dummy variables o nazwach "var.name: (level1)"
factorToDummy <- function(dtable, var.name){
  stopifnot(is.data.table(dtable))
  stopifnot(var.name %in% names(dtable))
  stopifnot(is.factor(dtable[, get(var.name)]))

  dtable[, paste0(var.name,": ",levels(get(var.name)))] -> new.names
  dtable[, (new.names) := transpose(lapply(get(var.name), FUN = function(x){x == levels(get(var.name))})) ]

  cat(paste("\nDodano zmienne dummy: ", paste0(new.names, collapse = ", ")))
}

Usage:

data <- data.table(data)
data[, x:= droplevels(x)]
factorToDummy(data, "x")

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

Spring Boot - Handle to Hibernate SessionFactory

It works with Spring Boot 2.1.0 and Hibernate 5

@PersistenceContext
private EntityManager entityManager;

Then you can create new Session by using entityManager.unwrap(Session.class)

Session session = null;
if (entityManager == null
    || (session = entityManager.unwrap(Session.class)) == null) {

    throw new NullPointerException();
}

example create query:

session.createQuery("FROM Student");

application.properties:

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

How to set a Header field on POST a form?

To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708


To add into particular ajax requests, this' how I implemented:

var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
 method: "POST",
 beforeSend: function(xhr) {
  xhr.setRequestHeader(token_header, token_value);
 },
 data: {form_field: $("#form_field").val()},
 success: doSomethingFunction,
 dataType: "json"
});

You must add the meta elements in the JSP, e.g.

<html>
<head>        
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <meta name="_csrf" content="${_csrf.token}"/>

To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708

Bootstrap 4 card-deck with number of columns based on viewport

Using Bootstrap 4.4.1, I was able to set the number of cards per deck using simple classes by adding some scss into the mix.

HTML

<div class="card-deck deck-1 deck-md-2 deck-lg-3">
   <div class="card">
      <h2 class="card-header">Card 1</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
   <div class="card">
      <h2 class="card-header">Card 2</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
   <div class="card">
      <h2 class="card-header">Card 3</h3>
      <div class="card-body">
          Card body
      </div>
      <div class="card-footer">
          Card footer
      </div>
   </div>
</div>

SCSS

// _card_deck_columns.scss
// add deck-X and deck-BP-X classes to select the number of cards per line
@for $i from 1 through $grid-columns {
  .deck-#{$i} > .card {
    $percentage: percentage(1 / $i);
    @if $i == 1 {
      $width: $percentage;
      flex-basis: $width;
      max-width: $width;
      margin-left: 0;
      margin-right: 0;
    } @else {
      $width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
      flex-basis: $width;
      max-width: $width;
    }
  }
}
@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
  @include media-breakpoint-up($breakpoint) {
    @for $i from 1 through $grid-columns {
      .deck#{$infix}-#{$i} > .card {
        $percentage: percentage(1 / $i);
        @if $i == 1 {
          $width: $percentage;
          flex-basis: $width;
          max-width: $width;
          margin-left: 0;
          margin-right: 0;
        } @else {
          $width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
          flex-basis: $width;
          max-width: $width;
          margin-left: $grid-gutter-width / 2;
          margin-right: $grid-gutter-width / 2;
        }
      }
    }
  }
}

CSS

.deck-1 > .card {
  flex-basis: 100%;
  max-width: 100%;
  margin-left: 0;
  margin-right: 0; }

.deck-2 > .card {
  flex-basis: calc(50% - 30px);
  max-width: calc(50% - 30px); }

.deck-3 > .card {
  flex-basis: calc(33.3333333333% - 30px);
  max-width: calc(33.3333333333% - 30px); }

.deck-4 > .card {
  flex-basis: calc(25% - 30px);
  max-width: calc(25% - 30px); }

.deck-5 > .card {
  flex-basis: calc(20% - 30px);
  max-width: calc(20% - 30px); }

.deck-6 > .card {
  flex-basis: calc(16.6666666667% - 30px);
  max-width: calc(16.6666666667% - 30px); }

.deck-7 > .card {
  flex-basis: calc(14.2857142857% - 30px);
  max-width: calc(14.2857142857% - 30px); }

.deck-8 > .card {
  flex-basis: calc(12.5% - 30px);
  max-width: calc(12.5% - 30px); }

.deck-9 > .card {
  flex-basis: calc(11.1111111111% - 30px);
  max-width: calc(11.1111111111% - 30px); }

.deck-10 > .card {
  flex-basis: calc(10% - 30px);
  max-width: calc(10% - 30px); }

.deck-11 > .card {
  flex-basis: calc(9.0909090909% - 30px);
  max-width: calc(9.0909090909% - 30px); }

.deck-12 > .card {
  flex-basis: calc(8.3333333333% - 30px);
  max-width: calc(8.3333333333% - 30px); }

.deck-1 > .card {
  flex-basis: 100%;
  max-width: 100%;
  margin-left: 0;
  margin-right: 0; }

.deck-2 > .card {
  flex-basis: calc(50% - 30px);
  max-width: calc(50% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-3 > .card {
  flex-basis: calc(33.3333333333% - 30px);
  max-width: calc(33.3333333333% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-4 > .card {
  flex-basis: calc(25% - 30px);
  max-width: calc(25% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-5 > .card {
  flex-basis: calc(20% - 30px);
  max-width: calc(20% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-6 > .card {
  flex-basis: calc(16.6666666667% - 30px);
  max-width: calc(16.6666666667% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-7 > .card {
  flex-basis: calc(14.2857142857% - 30px);
  max-width: calc(14.2857142857% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-8 > .card {
  flex-basis: calc(12.5% - 30px);
  max-width: calc(12.5% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-9 > .card {
  flex-basis: calc(11.1111111111% - 30px);
  max-width: calc(11.1111111111% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-10 > .card {
  flex-basis: calc(10% - 30px);
  max-width: calc(10% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-11 > .card {
  flex-basis: calc(9.0909090909% - 30px);
  max-width: calc(9.0909090909% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

.deck-12 > .card {
  flex-basis: calc(8.3333333333% - 30px);
  max-width: calc(8.3333333333% - 30px);
  margin-left: 15px;
  margin-right: 15px; }

@media (min-width: 576px) {
  .deck-sm-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-sm-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-sm-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 768px) {
  .deck-md-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-md-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-md-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 992px) {
  .deck-lg-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-lg-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-lg-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }
@media (min-width: 1200px) {
  .deck-xl-1 > .card {
    flex-basis: 100%;
    max-width: 100%;
    margin-left: 0;
    margin-right: 0; }

  .deck-xl-2 > .card {
    flex-basis: calc(50% - 30px);
    max-width: calc(50% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-3 > .card {
    flex-basis: calc(33.3333333333% - 30px);
    max-width: calc(33.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-4 > .card {
    flex-basis: calc(25% - 30px);
    max-width: calc(25% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-5 > .card {
    flex-basis: calc(20% - 30px);
    max-width: calc(20% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-6 > .card {
    flex-basis: calc(16.6666666667% - 30px);
    max-width: calc(16.6666666667% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-7 > .card {
    flex-basis: calc(14.2857142857% - 30px);
    max-width: calc(14.2857142857% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-8 > .card {
    flex-basis: calc(12.5% - 30px);
    max-width: calc(12.5% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-9 > .card {
    flex-basis: calc(11.1111111111% - 30px);
    max-width: calc(11.1111111111% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-10 > .card {
    flex-basis: calc(10% - 30px);
    max-width: calc(10% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-11 > .card {
    flex-basis: calc(9.0909090909% - 30px);
    max-width: calc(9.0909090909% - 30px);
    margin-left: 15px;
    margin-right: 15px; }

  .deck-xl-12 > .card {
    flex-basis: calc(8.3333333333% - 30px);
    max-width: calc(8.3333333333% - 30px);
    margin-left: 15px;
    margin-right: 15px; } }

HTML5 <video> element on Android

After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format. So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers. I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:

if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');        
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

HTML inside Twitter Bootstrap popover

I really hate to put long HTML inside of the attribute, here is my solution, clear and simple (replace ? with whatever you want):

<a class="btn-lg popover-dismiss" data-placement="bottom" data-toggle="popover" title="Help">
    <h2>Some title</h2>
    Some text
</a>

then

var help = $('.popover-dismiss');
help.attr('data-content', help.html()).text(' ? ').popover({trigger: 'hover', html: true});

How does one Display a Hyperlink in React Native App?

for the React Native, there is library to open Hyperlinks in App. https://www.npmjs.com/package/react-native-hyperlink

In addition to this, i suppose you will need to check url and best approach is Regex. https://www.npmjs.com/package/url-regex

How do I search for names with apostrophe in SQL Server?

SELECT     *
FROM Header WHERE (userID LIKE '%''%')

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

How to split the screen with two equal LinearLayouts?

In order to split the ui into two equal parts you can use weightSum of 2 in the parent LinearLayout and assign layout_weight of 1 to each as shown below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

        </LinearLayout>

       <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

       </LinearLayout>


</LinearLayout>

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

Object reference not set to an instance of an object.

strSearch in this case is probably null (not simply empty).

Try using

String.IsNullOrEmpty(strSearch)

if you are just trying to determine if the string doesn't have any contents.

Apply Calibri (Body) font to text

If there is space between the letters of the font, you need to use quote.

font-family:"Calibri (Body)";

Convert Year/Month/Day to Day of Year in Python

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

How to import a bak file into SQL Server Express

To do this via TSQL (ssms query window or sqlcmd.exe) just run:

RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'

To do it via GUI - open SSMS, right click on Databases and follow the steps below

enter image description here enter image description here

How to sort a list of objects based on an attribute of the objects?

It looks much like a list of Django ORM model instances.

Why not sort them on query like this:

ut = Tag.objects.order_by('-count')

Reset ID autoincrement ? phpmyadmin

You can also do this in phpMyAdmin without writing SQL.

  • Click on a database name in the left column.
  • Click on a table name in the left column.
  • Click the "Operations" tab at the top.
  • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
  • Input desired value and click the "Go" button below.

Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

C++ static virtual members?

Maybe you can try my solution below:

class Base {
public:
    Base(void);
    virtual ~Base(void);

public:
    virtual void MyVirtualFun(void) = 0;
    static void  MyStaticFun(void) { assert( mSelf != NULL); mSelf->MyVirtualFun(); }
private:
    static Base* mSelf;
};

Base::mSelf = NULL;

Base::Base(void) {
    mSelf = this;
}

Base::~Base(void) {
    // please never delete mSelf or reset the Value of mSelf in any deconstructors
}

class DerivedClass : public Base {
public:
    DerivedClass(void) : Base() {}
    ~DerivedClass(void){}

public:
    virtual void MyVirtualFun(void) { cout<<"Hello, it is DerivedClass!"<<endl; }
};

int main() {
    DerivedClass testCls;
    testCls.MyStaticFun(); //correct way to invoke this kind of static fun
    DerivedClass::MyStaticFun(); //wrong way
    return 0;
}

How do I enable saving of filled-in fields on a PDF form?

There is a setting inside the PDF file that turns on the allow saving with data bit. However, it requires that you have a copy of Adobe Acrobat installed to change the bit.

The only other option is to print it to a PDF print driver which would save the data merged with the pdf file.

UPDATE: The relevant information from adobe is at: http://www.adobeforums.com/webx?13@@.3bbb313f/7

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

How to properly validate input values with React.JS?

I recently spent a week studying lot of solutions to validate my forms in an app. I started with all the most stared one but I couldn't find one who was working as I was expected. After few days, I became quite frustrated until i found a very new and amazing plugin: https://github.com/kettanaito/react-advanced-form

The developper is very responsive and his solution, after my research, merit to become the most stared one from my perspective. I hope it could help and you'll appreciate.

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

Use a negative lookahead and a negative lookbehind:

> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']

In other words, you always split by \s (whitespace), and only split by commas and periods if they are not followed (?!\d) or preceded (?<!\d) by a digit.

DEMO.

EDIT: As per @verdesmarald comment, you may want to use the following instead:

> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']

This will split "1.2,a,5" into ["1.2", "a", "5"].

DEMO.

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

In my case it works just commenting (or deleting) the anonymousAuthentication property:

 <security>
     <authentication>
         <!--<anonymousAuthentication enabled="true" />-->
     </authentication>
 </security>

C#: Looping through lines of multiline string

To update this ancient question for .NET 4, there is now a much neater way:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Sublime Text 3 how to change the font size of the file sidebar?

I use Soda Dark 3 with icons enabled. So by just renaming it erases all the icons enabled with it. So I just leave the Default as it is and created a new file Soda Dark 3.sublime-theme and just have the following in the content

[
{
    "class": "label_control",
    "color": [150, 25, 25],
    "shadow_color": [24, 24, 24],
    "shadow_offset": [0, -1],
    "font.size": 16,
    "font.bold": true
},

]

So in Mac is it at /Users/gugovind/Library/Application Support/Sublime Text 3/Packages/User/

Why is it that "No HTTP resource was found that matches the request URI" here?

Your problems have nothing to do with POST/GET but only with how you specify parameters in RouteAttribute. To ensure this, I added support for both verbs in my samples.

Let's go back to two very simple working examples.

[Route("api/deliveryitems/{anyString}")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsOne(string anyString)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

And

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsTwo(string anyString = "default")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

The first sample says that the "anyString" is a path segment parameter (part of the URL).

First sample example URL is:

  • localhost:xxx/api/deliveryItems/dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"

The second sample says that the "anyString" is a query string parameter (optional here since a default value has been provided, but you can make it non-optional by simply removing the default value).

Second sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"
  • localhost:xxx/api/deliveryItems
    • returns "default"

Of course, you can make it even more complex, like with this third sample:

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsThree(string anyString, string anotherString = "anotherDefault")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString + "||" + anotherString);
}

Third sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||anotherDefault"
  • localhost:xxx/api/deliveryItems
    • returns "No HTTP resource was found that matches the request URI ..." (parameter anyString is mandatory)
  • localhost:xxx/api/deliveryItems?anotherString=bluberb&anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||bluberb"
    • note that the parameters have been reversed, which does not matter, this is not possible with "URL-style" of first example

When should you use path segment or query parameters? Some advice has already been given here: REST API Best practices: Where to put parameters?

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

Why are unnamed namespaces used and what are their benefits?

An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.

There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

How do I get into a Docker container's shell?

To bash into a running container, type this:

docker exec -t -i container_name /bin/bash

or

docker exec -ti container_name /bin/bash

or

docker exec -ti container_name sh

C#: easiest way to populate a ListBox from a List

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

Notepad++ change text color?

You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.

Sample for your reference here.

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

Replace multiple characters in a C# string

If you are feeling particularly clever and don't want to use Regex:

char[] separators = new char[]{' ',';',',','\r','\t','\n'};

string s = "this;is,\ra\t\n\n\ntest";
string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
s = String.Join("\n", temp);

You could wrap this in an extension method with little effort as well.

Edit: Or just wait 2 minutes and I'll end up writing it anyway :)

public static class ExtensionMethods
{
   public static string Replace(this string s, char[] separators, string newVal)
   {
       string[] temp;

       temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
       return String.Join( newVal, temp );
   }
}

And voila...

char[] separators = new char[]{' ',';',',','\r','\t','\n'};
string s = "this;is,\ra\t\n\n\ntest";

s = s.Replace(separators, "\n");

fatal: could not create work tree dir 'kivy'

You need to ensure you are in a directory in which you have write permission. This might not be the directory in which Git is in once you open the terminal. In my case (Widows 10) I had to use the cd command to change the directory to the root directory (C:) After that it worked just fine.

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

How do I escape spaces in path for scp copy in Linux?

works

scp localhost:"f/a\ b\ c" .

scp localhost:'f/a\ b\ c' .

does not work

scp localhost:'f/a b c' .

The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails

To see this in action, start a shell with the -vx options ie bash -vx and it will display the interpolated version of the command as it runs it.

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

I had this issue and was able to fix it by adding constraints to determine the max with for a label.

When dropping a multiline label in there is not constraint set to enforce the width inside the parent view. This is where the new PreferredMaxWidth comes into play. On iOS 7 and earlier you have to define the max width yourself. I simply added a 10px constraint to the left and right hand side of the label.

You can also add a <= width constraint which also fixes the issue.

So this is not actually a bug, you simply have to define the max width yourself. The explicit option mention in other answer will also work as you are setting this width value however you will have to modify this value if you want the max width to change based on the parent width (as you have explicitly set the width).

My above solution ensures the width is always maintained no matter how big the parent view is.

how to convert binary string to decimal?

function binaryToDecimal(string) {
    let decimal = +0;
    let bits = +1;
    for(let i = 0; i < string.length; i++) {
        let currNum = +(string[string.length - i - 1]);
        if(currNum === 1) {
            decimal += bits;
        }
        bits *= 2;
    }
    console.log(decimal);
}

Find in Files: Search all code in Team Foundation Server

In my case, writing a small utility in C# helped. Links that helped me - http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html

How to list files of a team project using tfs api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;

namespace TFSSearch
{
class Program
{
    static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" };  //Text to search
    static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html", 
                                           "*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions

    static void Main(string[] args)
    {
        try
        {
            var tfs = TfsTeamProjectCollectionFactory
             .GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)

            tfs.EnsureAuthenticated();

            var versionControl = tfs.GetService<VersionControlServer>();


            StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
            var allProjs = versionControl.GetAllTeamProjects(true);
            foreach (var teamProj in allProjs)
            {
                foreach (var filePattern in filePatterns)
                {
                    var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
                                .Where(i => !i.ServerItem.Contains("_ReSharper"));  //skipping resharper stuff
                    foreach (var item in items)
                    {
                        List<string> lines = SearchInFile(item);
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine("FILE:" + item.ServerItem);
                            outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
                            outputFile.WriteLine();
                        }
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine();
                        }
                    }
                }
                outputFile.Flush();
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }
        Console.WriteLine("========");
        Console.Read();
    }

    // Define other methods and classes here
    private static List<string> SearchInFile(Item file)
    {
        var result = new List<string>();

        try
        {
            var stream = new StreamReader(file.DownloadFile(), Encoding.Default);

            var line = stream.ReadLine();
            var lineIndex = 0;

            while (!stream.EndOfStream)
            {
                if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
                    result.Add("=== Line " + lineIndex + ": " + line.Trim());

                line = stream.ReadLine();
                lineIndex++;
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }

        return result;
    }
}
}

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

What are the safe characters for making URLs?

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

pod install -bash: pod: command not found

I'm using OS Catalina and used the solution of Babul Prabhakar. But when I closed the terminal, pod still was unable.

So I put the exports:

$ export GEM_HOME=$HOME/Software/ruby
$ export PATH=$PATH:$HOME/Software/ruby/bin

inside this file(put this command below inside the terminal):

nano ~/.bash_profile

Then save the file, close the terminal and open it up again and type:

pod --version

Handling click events on a drawable within an EditText

and if drawable is on the left, this will help you. (for those work with RTL layout)

 editComment.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getRawX() <= (searchbox.getLeft() + searchbox.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) {
                                     // your action here

                 return true;
                }
            }
            return false;
        }
    });

Android getText from EditText field

Try this.

EditText text = (EditText)findViewById(R.id.edittext1);
String  str = text.getText().toString().trim();

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

Get the first element of each tuple in a list in Python

If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>

How do I get the size of a java.sql.ResultSet?

ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
  // do your standard per row stuff
}

How to use Git and Dropbox together?

Now in 2014, I have been using Git and Dropbox for about one year and a half without problem. Some points though:

  • All my machines using Dropbox are on Windows, different versions (7 to 8) + 1 mac.
  • I do not share the repository with someone else, so I am the only one to modify it.
  • git push pushes to a remote repository, so that if it ever gets corrupted, I can easily recover it.
  • I had to create aliases in C:\Users with mklink /D link target because some libraries were pointed to absolute locations.

Calendar Recurring/Repeating Events - Best Storage Method

Sounds very much like MySQL events that are stored in system tables. You can look at the structure and figure out which columns are not needed:

   EVENT_CATALOG: NULL
    EVENT_SCHEMA: myschema
      EVENT_NAME: e_store_ts
         DEFINER: jon@ghidora
      EVENT_BODY: SQL
EVENT_DEFINITION: INSERT INTO myschema.mytable VALUES (UNIX_TIMESTAMP())
      EVENT_TYPE: RECURRING
      EXECUTE_AT: NULL
  INTERVAL_VALUE: 5
  INTERVAL_FIELD: SECOND
        SQL_MODE: NULL
          STARTS: 0000-00-00 00:00:00
            ENDS: 0000-00-00 00:00:00
          STATUS: ENABLED
   ON_COMPLETION: NOT PRESERVE
         CREATED: 2006-02-09 22:36:06
    LAST_ALTERED: 2006-02-09 22:36:06
   LAST_EXECUTED: NULL
   EVENT_COMMENT:

How to pass text in a textbox to JavaScript function?

You could just get the input value in the onclick-event like so:

onclick="execute(document.getElementById('textbox1').value);"

You would of course have to add an id to your textbox

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

IE9 jQuery AJAX with CORS returns "Access is denied"

Complete instructions on how to do this using the "jQuery-ajaxTransport-XDomainRequest" plugin can be found here: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest#instructions

This plugin is actively supported, and handles HTML, JSON and XML. The file is also hosted on CDNJS, so you can directly drop the script into your page with no additional setup: http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js

Python: download a file from an FTP server

requests library doesn't support ftp links.

To download a file from FTP server you could:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
#   urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')

Or:

import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Python3:

import shutil
import urllib.request as request
from contextlib import closing

with closing(request.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

SQL LIKE condition to check for integer?

If you want to search as string, you can cast to text like this:

SELECT * FROM books WHERE price::TEXT LIKE '123%'

Using ffmpeg to change framerate

You may consider using fps filter. It won't change the video playback speed:

ffmpeg -i <input> -filter:v fps=fps=30 <output>

Worked nice for reducing fps from 59.6 to 30.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

ISO_8859_1 Worked for me! I was reading text file with comma separated values

Angular 2 Scroll to top on Route Change

For everyone who is looking for a solution and read up to this post. The

imports: [
  RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'
  }),
  ...
]

doesn't answer the question of the topic. If we look into Angular source code then we could read there interesting lines:

enter image description here

So this stuff will only work on back navigation. One of the solutions could be something like:

constructor(router: Router) {

    router.events
        .pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
        .subscribe(() => {
            this.document.querySelector('#top').scrollIntoView();
        });
}

This will look on each navigation to the div with that id and scroll to it;

Another way of doing that is to use the same logic but with help of decorator or directive which will allow you to select where and when to scroll top;

How can I commit a single file using SVN over a network?

You have a file myFile.txt you want to commit.

The right procedure is :

  1. Move to the file folder
  2. svn up
  3. svn commit myFile.txt -m "Insert here a commit message!!!"

Hope this will help someone.

How can I add additional PHP versions to MAMP

Maybe easy like this?

Compiled binaries of the PHP interpreter can be found at http://www.mamp.info/en/ downloads/index.html . Drop this downloaded folder into your /Applications/MAMP/bin/php! directory. Close and re-open your MAMP PRO application. Your new PHP version should now appear in the PHP drop down menu. MAMP PRO will only support PHP versions from the downloads page.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

ListView.FocusedItem.Index 

or you can use foreach loop like this

int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
    if (itm.Selected)
    {
        index= itm.Index;
    }
}

Is there a way to iterate over a range of integers?

It was suggested by Mark Mishyn to use slice but there is no reason to create array with make and use in for returned slice of it when array created via literal can be used and it's shorter

for i := range [5]int{} {
        fmt.Println(i)
}

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I encountered this issue because I used setState instead of state in the constructor.

EXAMPLE

Change the following incorrect code

constructor(props) {
  super(props);
  this.setState({
    key: ''
  });
}

to

constructor(props) {
  super(props);
  this.state = {
    key: ''
  }; 
}

extract column value based on another column pandas dataframe

You can try query, which is less typing:

df.query('B==3')['A']

What causes a Python segmentation fault?

I understand you've solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.

The way to do it, is operating system dependant. In linux, you can check with the command ulimit -s your current value and you can increase it with ulimit -s <new_value>

Try doubling the previous value and continue doubling if it does not work, until you find one that does or run out of memory.

Get everything after the dash in a string in JavaScript

AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).

Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.

Access mysql remote database from command line

Try this command mysql -uuser -hhostname -PPORT -ppassword.

I faced a similar situation and later when mysql port for host was entered with the command, it was solved.

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

Check if element at position [x] exists in the list

if (list.Count > desiredIndex && list[desiredIndex] != null)
{
    // logic
}

error: expected declaration or statement at end of input in c

You probably have syntax error. You most likely forgot to put a } or ; somewhere above this function.

Changing the color of an hr element

Since i don't have reputation to comment, i will give here a few ideas.

if you want a css variable height, take off all borders and give a background color.

    hr{
        height:2px;
        border:0px;
        background:green;
        margin:0px;/*sometimes useful*/
    }
    /*Doesn't work in ie7 and below and in Quirks Mode*/

if you want simply a style that you know that will work (example: to replace a border in a ::before element for most email clients or

    hr{
        height:0px;
        border:0px;
        border-top:2px solid blue;
        margin:0px;/*useful sometimes*/
    }

In both ways, if you set a width, it will always have it's size.

No need to set display:block; for this.

To be totally safe, you can mix both, 'cause some browsers can get confused with height:0px;:

    hr{
        height:1px;
        border:0px;
        background:blue;
        border-top:1px solid blue;
        margin:0px;/*useful sometimes*/
    }

With this method you can be sure that it will have at least 2px in height.

It's a line more, but safety is safety.

This is the method you should use to be compatible with almost everything.

Remember: Gmail only detects inline css and some email clients may not support backgrounds or borders. If one fails, you will still have a 1px line. Better than nothing.

In the worst cases, you can try to add color:blue;.

In the worst of the worst cases, you can try to use a <font color="blue"></font> tag and put your precious <hr/> tag inside it. It will inherit the <font></font> tag color.

With this method, you WILL want to do like this: <hr width="50" align="left"/>.

Example:

    <span>
        awhieugfrafgtgtfhjjygfjyjg
        <font color="#42B3E5"><hr width="50" align="left"/></font>
    </span>
    <!--Doesn't work in ie7 and below and in Quirks Mode-->

Here is a link for you to check: http://jsfiddle.net/sna2D/

How can I load the contents of a text file into a batch file variable?

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

How can I send large messages with Kafka (over 15MB)?

You need to override the following properties:

Broker Configs($KAFKA_HOME/config/server.properties)

  • replica.fetch.max.bytes
  • message.max.bytes

Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine

  • fetch.message.max.bytes

Restart the server.

look at this documentation for more info: http://kafka.apache.org/08/configuration.html

iOS UIImagePickerController result image orientation after upload

If you enable editing, then the edited image (as opposed to the original) will be oriented as expected:

UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.allowsEditing = YES;
// set delegate and present controller

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *photo = [info valueForKey:UIImagePickerControllerEditedImage];
    // do whatever
}

Enabling editing allows the user to resize and move the image before tapping "Use Photo"

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

I got the same errors. Mysql was running as a standalone application before I started phpMyAdmin.

I just stopped mysql Then sudo /Applications/XAMPP/xamppfiles/xampp stop sudo /Applications/XAMPP/xamppfiles/xampp start

It worked fine

Python: how to capture image from webcam on click using OpenCV

This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

output

enter image description here

Also, You can check out my GitHub code

Forcing to download a file using PHP

This cannot be done reliably, since it's up to the browser to decide what to do with an URL it's been asked to retrieve.

You can suggest to the browser that it should offer to "save to disk" right away by sending a Content-disposition header:

header("Content-disposition: attachment");

I'm not sure how well this is supported by various browsers. The alternative is to send a Content-type of application/octet-stream, but that is a hack (you're basically telling the browser "I'm not telling you what kind of file this is" and depending on the fact that most browsers will then offer a download dialog) and allegedly causes problems with Internet Explorer.

Read more about this in the Web Authoring FAQ.

Edit You've already switched to a PHP file to deliver the data - which is necessary to set the Content-disposition header (unless there are some arcane Apache settings that can also do this). Now all that's left to do is for that PHP file to read the contents of the CSV file and print them - the filename=example.csv in the header only suggests to the client browser what name to use for the file, it does not actually fetch the data from the file on the server.

Select arrow style change

Working with just one class:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

http://jsfiddle.net/qhCsJ/4120/

How do I change the data type for a column in MySQL?

alter table table_name modify column_name int(5)

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

how to set image from url for imageView

You can also let Square's Picasso library do the heavy lifting:

Picasso
    .get()
    .load("http://...")
    .into(imageView);

As a bonus, you get caching, transformations, and more.

How to split a comma separated string and process in a loop using JavaScript

Like this:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

How To Set Up GUI On Amazon EC2 Ubuntu server

This can be done. Following are the steps to setup the GUI

Create new user with password login

sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui

sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes

sudo /etc/init.d/ssh restart

Setting up ui based ubuntu machine on AWS.

In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:

sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server

Then run following commands and enter the login password for vnc connection:

su - awsgui

vncserver

vncserver -kill :1

vim /home/awsgui/.vnc/xstartup

Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads

exec sh /etc/X11/xinit/xinitrc. 

When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.

Then start vnc server again.

vncserver

You can download xtightvncviewer to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients

In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.

Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html

Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/

Port opening on console

sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT

If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.

vncserver

Throw HttpResponseException or return Request.CreateErrorResponse?

Another case for when to use HttpResponseException instead of Response.CreateResponse(HttpStatusCode.NotFound), or other error status code, is if you have transactions in action filters and you want the transactions to be rolled back when returning an error response to the client.

Using Response.CreateResponse will not roll the transaction back, whereas throwing an exception will.

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

How to set the color of an icon in Angular Material?

Here's a move that I'm using to set the color dynamically, it defaults to primary theme if the variable is undefined.

in your component define your color

  /**Sets the button colors - Defaults to primary them color */
  @Input('buttonsColor') _buttonsColor: string

in your style (sass here) - this forces the icon to use the color of it's container

.mat-custom{
  .mat-icon, .mat-icon-button{
     color:inherit !important;
  }  
}

in your html surround your button with a div

        <div [class.mat-custom]="!!_buttonsColor" [style.color]="_buttonsColor"> 
            <button mat-icon-button (click)="doSomething()">
                <mat-icon [svgIcon]="'refresh'" color="primary"></mat-icon>
            </button>
        </div>

Hover and Active only when not disabled

.button:active:hover:not([disabled]) {
    /*your styles*/
}

You can try this..

How to create a directory using Ansible

to create directory

ansible host_name -m file -a "dest=/home/ansible/vndir state=directory"

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Excel VBA Check if directory exists error

Use the FolderExists method of the Scripting object.

Public Function dirExists(s_directory As String) As Boolean
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    dirExists = oFSO.FolderExists(s_directory)
End Function

gcloud command not found - while installing Google Cloud SDK

This worked for me :

After saying Y to Modify profile to update your $PATH and enable bash completion? (Y/n)?

Google initiation is prompting this : Enter a path to an rc file to update, or leave blank to use and the default path was : [/Users/MY_USERSAME/.bash_profile]: but instead of pressing enter, I wrote : /Users/MY_USERNAME/.bashrc to change the path.

This would overwrite the default location that Google suggest.

Then, I only had to do source ~/.bashrc and everything works now!

YouTube embedded video: set different thumbnail

This solution is HTML and CSS based using z-index and hover, which works if JS is disabled or the video isn't yours (since you can add a thumbnail in YouTube).

<style>
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
}
.videoWrapper .video-modal-poster img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.videoWrapper .video-modal-poster:hover img {
  z-index:0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>
<div class="videoWrapper">
  <a href="#" class="video-modal-poster">
    <img alt="" src="" width="353" height="199" />
    <iframe width="353" height="199" src="https://www.youtube.com/embed/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
  </a>
</div>

Making HTTP Requests using Chrome Developer tools

Yes, there is a way without any 3rd party extension.

I've built javascript-snippet (which you can add as browser-bookmark) and then activate on any site to monitor & modify the requests. :

enter image description here

For further instructions, review the github page.

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

How to disable an Android button?

You can't enable it or disable it in your XML (since your layout is set at runtime), but you can set if it's clickable at the launch of the activity with android:clickable.

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

Couldn't connect to server 127.0.0.1:27017

In windows run cmd as Admin:

  1. Create directory:

    mkdir c:\mongo\data\db

  2. Install service:

    mongod.exe --install --logpath c:\mongo\logs --logappend --bind_ip 127.0.0.1 --dbpath c:\mongo\data\db --directoryperdb

  3. Start MongoDB:

    net start MongoDB

4.Start Mongo Shell:

c:\mongo\bin\mongo.exe

This solution work fine for me

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

Understand this has been solved, but the solution provided above might not work in all situation.

For my case,

<div style="height: 490px; position:relative; overflow:hidden">
    <div id="map-canvas"></div>
</div>

fill an array in C#

int[] arr = Enumerable.Repeat(42, 10000).ToArray();

I believe that this does the job :)

Getting SyntaxError for print with keyword argument end=' '

Basically, it occurs in python2.7 here is my code of how it works:

  i=5
while(i):
    print i,
    i=i-1
Output:
5 4 3 2 1

How to tell git to use the correct identity (name and email) for a given project?

If you don't use the --global parameter it will set the variables for the current project only.

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

How to get array keys in Javascript?

Say your array looked like arr = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 } ] (or possibly other keys) you could do

arr.map((o) => {
    return Object.keys(o)
}).reduce((prev, curr) => {
    return prev.concat(curr)
}).filter((col, i, array) => {
    return array.indexOf(col) === i
});

["a", "b", "c"]

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

Spring Boot 1.4 Use this for Javascript HTML Json all compressions.

server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript

CSS:Defining Styles for input elements inside a div

CSS 3

divContainer input[type="text"] {
    width:150px;
}

CSS2 add a class "text" to the text inputs then in your css

.divContainer.text{
    width:150px;
}

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Can I write or modify data on an RFID tag?

I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).

I'd recomment that you look at the OpenPCD platform if you are into development.

This is also of interest regarding the cryptographic functions in some RFID cards.

How to check if IsNumeric

There's the TryParse method, which returns a bool indicating if the conversion was successful.

Azure SQL Database "DTU percentage" metric

Still not cool enough to comment, but regarding @vladislav's comment the original article was fairly old. Here is an update document regarding DTU's, which would help answer the OP's question.

https://docs.microsoft.com/en-us/azure/sql-database/sql-database-what-is-a-dtu

What is git tag, How to create tags & How to checkout git remote tag(s)

Let's start by explaining what a tag in git is

enter image description here

A tag is used to label and mark a specific commit in the history.
It is usually used to mark release points (eg. v1.0, etc.).

Although a tag may appear similar to a branch, a tag, however, does not change. It points directly to a specific commit in the history and will not change unless explicitly updated.

enter image description here


You will not be able to checkout the tags if it's not locally in your repository so first, you have to fetch the tags to your local repository.

First, make sure that the tag exists locally by doing

# --all will fetch all the remotes.
# --tags will fetch all tags as well
$ git fetch --all --tags --prune

Then check out the tag by running

$ git checkout tags/<tag_name> -b <branch_name>

Instead of origin use the tags/ prefix.


In this sample you have 2 tags version 1.0 & version 1.1 you can check them out with any of the following:

$ git checkout A  ...
$ git checkout version 1.0  ...
$ git checkout tags/version 1.0  ...

All of the above will do the same since the tag is only a pointer to a given commit.

enter image description here
origin: https://backlog.com/git-tutorial/img/post/stepup/capture_stepup4_1_1.png


How to see the list of all tags?

# list all tags
$ git tag

# list all tags with given pattern ex: v-
$ git tag --list 'v-*'

How to create tags?

There are 2 ways to create a tag:

# lightweight tag 
$ git tag 

# annotated tag
$ git tag -a

The difference between the 2 is that when creating an annotated tag you can add metadata as you have in a git commit:
name, e-mail, date, comment & signature

enter image description here

How to delete tags?

Delete a local tag

$ git tag -d <tag_name>
Deleted tag <tag_name> (was 000000)

Note: If you try to delete a non existig Git tag, there will be see the following error:

$ git tag -d <tag_name>
error: tag '<tag_name>' not found.

Delete remote tags

# Delete a tag from the server with push tags
$ git push --delete origin <tag name>

How to clone a specific tag?

In order to grab the content of a given tag, you can use the checkout command. As explained above tags are like any other commits so we can use checkout and instead of using the SHA-1 simply replacing it with the tag_name

Option 1:

# Update the local git repo with the latest tags from all remotes
$ git fetch --all

# checkout the specific tag
$ git checkout tags/<tag> -b <branch>

Option 2:

Using the clone command

Since git supports shallow clone by adding the --branch to the clone command we can use the tag name instead of the branch name. Git knows how to "translate" the given SHA-1 to the relevant commit

# Clone a specific tag name using git clone 
$ git clone <url> --branch=<tag_name>

git clone --branch=

--branch can also take tags and detaches the HEAD at that commit in the resulting repository.


How to push tags?

git push --tags

To push all tags:

# Push all tags
$ git push --tags 

Using the refs/tags instead of just specifying the <tagname>.

Why?

  • It's recommended to use refs/tags since sometimes tags can have the same name as your branches and a simple git push will push the branch instead of the tag

To push annotated tags and current history chain tags use:

git push --follow-tags

This flag --follow-tags pushes both commits and only tags that are both:

  • Annotated tags (so you can skip local/temp build tags)
  • Reachable tags (an ancestor) from the current branch (located on the history)

enter image description here

From Git 2.4 you can set it using configuration

$ git config --global push.followTags true

Cheatsheet: enter image description here


How to save data in an android app

OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)

I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.

So you really need a multi-point system:

1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.

2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.

3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.

3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.

File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
    fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
    fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
    fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory

I recommend simple CSV files for your data, so that other applications can read them easily.

Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be

0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:

0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

How to properly assert that an exception gets raised in pytest?

This solution is what we are using:

def test_date_invalidformat():
    """
    Test if input incorrect data will raises ValueError exception
    """
    date = "06/21/2018 00:00:00"
    with pytest.raises(ValueError):
        app.func(date) #my function to be tested

Please refer to pytest, https://docs.pytest.org/en/latest/reference.html#pytest-raises

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

Entity Framework vs LINQ to SQL

There are a number of obvious differences outlined in that article @lars posted, but short answer is:

  • L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
  • L2S will only work with SQL Server (as far as I know)
  • EF allows mapping a single class to multiple tables
  • EF will handle M-M relationships
  • EF will have ability to target any ADO.NET data provider

The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

SQL Joins Vs SQL Subqueries (Performance)?

You can use an Explain Plan to get an objective answer.

For your problem, an Exists filter would probably perform the fastest.

JRE installation directory in Windows

In the command line you can type java -version

How to use mongoimport to import csv

Check that you have a blank line at the end of the file, otherwise the last line will be ignored on some versions of mongoimport

How can I rename a field for all documents in MongoDB?

If ever you need to do the same thing with mongoid:

Model.all.rename(:old_field, :new_field)

UPDATE

There is change in the syntax in monogoid 4.0.0:

Model.all.rename(old_field: :new_field)

How can I remove a style added with .css() function?

There are several ways to remove a CSS property using jQuery:

1. Setting the CSS property to its default (initial) value

.css("background-color", "transparent")

See the initial value for the CSS property at MDN. Here the default value is transparent. You can also use inherit for several CSS properties to inherite the attribute from its parent. In CSS3/CSS4, you may also use initial, revert or unset but these keywords may have limited browser support.

2. Removing the CSS property

An empty string removes the CSS property, i.e.

.css("background-color","")

But beware, as specified in jQuery .css() documentation, this removes the property but it has compatibilty issues with IE8 for certain CSS shorthand properties, including background.

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or element.

3. Removing the whole style of the element

.removeAttr("style")

SQL Server IN vs. EXISTS Performance

I've done some testing on SQL Server 2005 and 2008, and on both the EXISTS and the IN come back with the exact same actual execution plan, as other have stated. The Optimizer is optimal. :)

Something to be aware of though, EXISTS, IN, and JOIN can sometimes return different results if you don't phrase your query just right: http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx

Installing PDO driver on MySQL Linux server

That's a good question, but I think you just misunderstand what you read.

Install PDO

The ./config --with-pdo-mysql is something you have to put on only if you compile your own PHP code. If you install it with package managers, you just have to use the command line given by Jany Hartikainen: sudo apt-get install php5-mysql and also sudo apt-get install pdo-mysql

Compatibility with mysql_

Apart from the fact mysql_ is really discouraged, they are both independent. If you use PDO mysql_ is not implicated, and if you use mysql_ PDO is not required.

If you turn off PDO without changing any line in your code, you won't have a problem. But since you started to connect and write queries with PDO, you have to keep it and give up mysql_.

Several years ago the MySQL team published a script to migrate to MySQLi. I don't know if it can be customised, but it's official.

CSS last-child selector: select last-element of specific class, not last child inside of parent?

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

How to remove "Server name" items from history of SQL Server Management Studio

Rather than deleting or renaming this file:

  1. Close SQL Server Management Studio.
  2. Find the appropriate file (see the other posts).
  3. Open the .bin in a text/hex editior like NotePad++.
  4. Search for the name of one of the servers and identify the line number.
  5. Make a copy of the .bin/.dat file.
  6. Delete that line. Make sure you delete the entire line, it's possible if you have many the line could wrap.
  7. Open SQL Server Management Studio. Your dropdown will be blank.

UIView Infinite 360 degree rotation animation?

David Rysanek's awesome answer updated to Swift 4:

import UIKit

extension UIView {

        func startRotating(duration: CFTimeInterval = 3, repeatCount: Float = Float.infinity, clockwise: Bool = true) {

            if self.layer.animation(forKey: "transform.rotation.z") != nil {
                return
            }

            let animation = CABasicAnimation(keyPath: "transform.rotation.z")
            let direction = clockwise ? 1.0 : -1.0
            animation.toValue = NSNumber(value: .pi * 2 * direction)
            animation.duration = duration
            animation.isCumulative = true
            animation.repeatCount = repeatCount
            self.layer.add(animation, forKey:"transform.rotation.z")
        }

        func stopRotating() {

            self.layer.removeAnimation(forKey: "transform.rotation.z")

        }   

    }
}

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

How to print the contents of RDD?

In python

   linesWithSessionIdCollect = linesWithSessionId.collect()
   linesWithSessionIdCollect

This will printout all the contents of the RDD

Exception of type 'System.OutOfMemoryException' was thrown. Why?

try to break your large data as much as possible because I already faced number of times this types of problem. In which I have above 10 Lakh records with 15 columns.

Python, HTTPS GET with basic authentication

Based on the @AndrewCox 's answer with some minor improvements:

from http.client import HTTPSConnection
from base64 import b64encode


client = HTTPSConnection("www.google.com")
user = "user_name"
password = "password"
headers = {
    "Authorization": "Basic {}".format(
        b64encode(bytes(f"{user}:{password}", "utf-8")).decode("ascii")
    )
}
client.request('GET', '/', headers=headers)
res = client.getresponse()
data = res.read()

Note, you should set encoding if you use bytes function instead of b"".

Laravel - display a PDF file in storage without forcing download?

Retrieving Files
$contents = Storage::get('file.jpg');

Downloading Files
return Storage::download('file.jpg');

File URLs
$url = Storage::url('file.jpg');