Programs & Examples On #Left join

A left join is an outer join which generates a result that contains all the records of the "left" table even when there are no matching records in other tables taking part in the join.

Entity framework left join

If UserGroups has a one to many relationship with UserGroupPrices table, then in EF, once the relationship is defined in code like:

//In UserGroups Model
public List<UserGroupPrices> UserGrpPriceList {get;set;}

//In UserGroupPrices model
public UserGroups UserGrps {get;set;}

You can pull the left joined result set by simply this:

var list = db.UserGroupDbSet.ToList();

assuming your DbSet for the left table is UserGroupDbSet, which will include the UserGrpPriceList, which is a list of all associated records from the right table.

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Insert using LEFT JOIN and INNER JOIN

You have to be specific about the columns you are selecting. If your user table had four columns id, name, username, opted_in you must select exactly those four columns from the query. The syntax looks like:

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

However, there does not appear to be any reason to join against user_permission here, since none of the columns from that table would be inserted into user. In fact, this INSERT seems bound to fail with primary key uniqueness violations.

MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT statements in your code, using the last insert id from the first query, or create an AFTER INSERT trigger on the primary table.

INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)

Or using a trigger:

CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
  INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

Difference between left join and right join in SQL Server

select fields 
from tableA --left
left join tableB --right
on tableA.key = tableB.key

The table in the from in this example tableA, is on the left side of relation.

tableA <- tableB
[left]------[right]

So if you want to take all rows from the left table (tableA), even if there are no matches in the right table (tableB), you'll use the "left join".

And if you want to take all rows from the right table (tableB), even if there are no matches in the left table (tableA), you will use the right join.

Thus, the following query is equivalent to that used above.

select fields
from tableB 
right join tableA on tableB.key = tableA.key

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

How to use mysql JOIN without ON condition?

See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/

You can use 'USING' instead of 'ON' as in the query

SELECT * FROM table1 LEFT JOIN table2 USING (id);

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

Select rows which are not present in other table

this can also be tried...

SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM   login_log l 
LEFT   JOIN (SELECT ip_location.ip, ip_location.hostname
             FROM ip_location
             WHERE ip_location.ip is null)tbl2

LINQ Inner-Join vs Left-Join

I think if you want to use extension methods you need to use the GroupJoin

var query =
    people.GroupJoin(pets,
                     person => person,
                     pet => pet.Owner,
                     (person, petCollection) =>
                        new { OwnerName = person.Name,
                              Pet = PetCollection.Select( p => p.Name )
                                                 .DefaultIfEmpty() }
                    ).ToList();

You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.

I think it's a little easier with the LINQ Query syntax

var query = (from person in context.People
             join pet in context.Pets on person equals pet.Owner
             into tempPets
             from pets in tempPets.DefaultIfEmpty()
             select new { OwnerName = person.Name, Pet = pets.Name })
            .ToList();

SQL SELECT from multiple tables

SELECT pid, cid, pname, name1, name2 
FROM customer1 c1, product p 
WHERE p.cid=c1.cid 
UNION SELECT pid, cid, pname, name1, name2 
FROM customer2 c2, product p 
WHERE p.cid=c2.cid;

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

How to return rows from left table not found in right table?

Try This

SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL

For more please read this article : Joins in Sql Server

enter image description here

Deleting rows with MySQL LEFT JOIN

If you are using "table as", then specify it to delete.

In the example i delete all table_1 rows which are do not exists in table_2.

DELETE t1 FROM `table_1` t1 LEFT JOIN `table_2` t2 ON t1.`id` = t2.`id` WHERE t2.`id` IS NULL

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

I would like to give another example in which multiple (3) joins are used.

 DataClasses1DataContext ctx = new DataClasses1DataContext();

        var Owners = ctx.OwnerMasters;
        var Category = ctx.CategoryMasters;
        var Status = ctx.StatusMasters;
        var Tasks = ctx.TaskMasters;

        var xyz = from t in Tasks
                  join c in Category
                  on t.TaskCategory equals c.CategoryID
                  join s in Status
                  on t.TaskStatus equals s.StatusID
                  join o in Owners
                  on t.TaskOwner equals o.OwnerID
                  select new
                  {
                      t.TaskID,
                      t.TaskShortDescription,
                      c.CategoryName,
                      s.StatusName,
                      o.OwnerName
                  };

LEFT JOIN only first row

Version without subselect:

   SELECT f.title,
          f.content,
          MIN(a.artist_name) artist_name
     FROM feeds f
LEFT JOIN feeds_artists fa ON fa.feed_id = f.id
LEFT JOIN artists a ON fa.artist_id = a.artist_id
 GROUP BY f.id

Left Join With Where Clause

The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.

ID and NAME columns are from the right side table, so are returned.

Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".

The below would return the result you were expecting:

    SELECT  a.*, b.Score
FROM    @Table1 a
    LEFT JOIN @Table2 b
       ON a.ID = b.T1_ID 
WHERE 1=1
AND a.Name = 'Flow'

The SQL applies a filter on the right hand table.

MySQL select rows where left join is null

SELECT table1.id 
FROM table1 
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one is NULL

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are only 3 joins:

  • A) Cross Join = Cartesian (E.g: Table A, Table B)
  • B) Inner Join = JOIN (E.g: Table A Join/Inner Join Table B)
  • C) Outer join:

       There are three type of outer join
       1)  Left Outer Join     = Left Join
       2)  Right Outer Join    = Right Join
       3)  Full Outer Join     = Full Join    
    

Hope it'd help.

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

Using IS NULL or IS NOT NULL on join conditions - Theory question

The WHERE clause is evaluated after the JOIN conditions have been processed.

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

Multiple left joins on multiple tables in one query

This kind of query should work - after rewriting with explicit JOIN syntax:

SELECT something
FROM   master      parent
JOIN   master      child ON child.parent_id = parent.id
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  parent.parent_id = 'rootID'

The tripping wire here is that an explicit JOIN binds before "old style" CROSS JOIN with comma (,). I quote the manual here:

In any case JOIN binds more tightly than the commas separating FROM-list items.

After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.

Just to make my point, this would work, too:

SELECT something
FROM   master parent
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
,      master child
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  child.parent_id = parent.id
AND    parent.parent_id = 'rootID'

But explicit JOIN syntax is generally preferable, as your case illustrates once again.

And be aware that multiple (LEFT) JOIN can multiply rows:

How can I set my Cygwin PATH to find javac?

To bring more prominence to the useful comment by @johanvdw:

If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/" somewhere in the file.

When Cygwin starts, it'll search directories in PATH and this one for executable files to run.

File count from a folder

.NET methods Directory.GetFiles(dir) or DirectoryInfo.GetFiles() are not very fast for just getting a total file count. If you use this file count method very heavily, consider using WinAPI directly, which saves about 50% of time.

Here's the WinAPI approach where I encapsulate WinAPI calls to a C# method:

int GetFileCount(string dir, bool includeSubdirectories = false)

Complete code:

[Serializable, StructLayout(LayoutKind.Sequential)]
private struct WIN32_FIND_DATA
{
    public int dwFileAttributes;
    public int ftCreationTime_dwLowDateTime;
    public int ftCreationTime_dwHighDateTime;
    public int ftLastAccessTime_dwLowDateTime;
    public int ftLastAccessTime_dwHighDateTime;
    public int ftLastWriteTime_dwLowDateTime;
    public int ftLastWriteTime_dwHighDateTime;
    public int nFileSizeHigh;
    public int nFileSizeLow;
    public int dwReserved0;
    public int dwReserved1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string cFileName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
    public string cAlternateFileName;
}

[DllImport("kernel32.dll")]
private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindNextFile(IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);

private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private const int FILE_ATTRIBUTE_DIRECTORY = 16;

private int GetFileCount(string dir, bool includeSubdirectories = false)
{
    string searchPattern = Path.Combine(dir, "*");

    var findFileData = new WIN32_FIND_DATA();
    IntPtr hFindFile = FindFirstFile(searchPattern, ref findFileData);
    if (hFindFile == INVALID_HANDLE_VALUE)
        throw new Exception("Directory not found: " + dir);

    int fileCount = 0;
    do
    {
        if (findFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
        {
            fileCount++;
            continue;
        }

        if (includeSubdirectories && findFileData.cFileName != "." && findFileData.cFileName != "..")
        {
            string subDir = Path.Combine(dir, findFileData.cFileName);
            fileCount += GetFileCount(subDir, true);
        }
    }
    while (FindNextFile(hFindFile, ref findFileData));

    FindClose(hFindFile);

    return fileCount;
}

When I search in a folder with 13000 files on my computer - Average: 110ms

int fileCount = GetFileCount(searchDir, true); // using WinAPI

.NET built-in method: Directory.GetFiles(dir) - Average: 230ms

int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;

Note: first run of either of the methods will be 60% - 100% slower respectively because the hard drive takes a little longer to locate the sectors. Subsequent calls will be semi-cached by Windows, I guess.

How to get screen dimensions as pixels in Android

This is not an answer for the OP, as he wanted the display dimensions in real pixels. I wanted the dimensions in "device-independent-pixels", and putting together answers from here https://stackoverflow.com/a/17880012/253938 and here https://stackoverflow.com/a/6656774/253938 I came up with this:

    DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
    int dpHeight = (int)(displayMetrics.heightPixels / displayMetrics.density + 0.5);
    int dpWidth = (int)(displayMetrics.widthPixels / displayMetrics.density + 0.5);

How to print full stack trace in exception?

Use a function like this:

    public static string FlattenException(Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

Then you can call it like this:

try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(FlattenException(we));
}

Is mathematics necessary for programming?

It's not required by a long shot, but...

As a trivial example--Without an understanding of geometry, you couldn't do a lot of stuff with squares and rectangles. (Every programmer has/gets geometry, so it's just an example).

Without trigonometry, there are certain things that are tough to do. Try to draw an analog clock with no understanding of trigonometry -- you can do it, but the process you have to go through is essentially re-inventing trigonometry.

Calculus is interesting. You'll probably never need it unless you design games, but calculus teaches you how to model things that act much more "Real world". For instance, if you try to model a tree falling, to get the speed right at every point along the arch you probably need a good deal of math.

On the other hand, it's just a matter of being exact. Anything you can do with calculus you can probably do with looping and approximations.

Beyond that, to make things even more life-like, you will probably need fractals and more advanced math.

If you are programming web sites and databases, you hardly need algebra 101.

Content Type text/xml; charset=utf-8 was not supported by service

I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to

Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory" 

and now you can compile & run your application successfully.

GIT commit as different user without email / or only email

It is all dependent on how you commit.

For example:

git commit -am "Some message"

will use your ~\.gitconfig username. In other words, if you open that file you should see a line that looks like this:

[user]
    email = [email protected]

That would be the email you want to change. If your doing a pull request through Bitbucket or Github etc. you would be whoever you're logged in as.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        **contentType: false,
        processData: false**
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try

last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)  

I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.

Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.

You query would be

UPDATE  student_queues SET  Deleted=0 ,  last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)  
 WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'

Cannot lower case button text in android studio

This is fixable in the application code by setting the button's TransformationMethod null, e.g.

mButton.setTransformationMethod(null);

How to send only one UDP packet with netcat?

I did not find the -q1 option on my netcat. Instead I used the -w1 option. Below is the bash script I did to send an udp packet to any host and port:

#!/bin/bash

def_host=localhost
def_port=43211

HOST=${2:-$def_host}
PORT=${3:-$def_port}

echo -n "$1" | nc -4u -w1 $HOST $PORT

python pip on Windows - command 'cl.exe' failed

If you want it really easy and a joy to automate, check out Chocolatey.org/install and you can basically copy and paste these commands and tweak it based on what versions of VC++ you need.

This command is taken from https://chocolatey.org/install

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Once you have chocolatey installed you can either close and reopen your Powershell terminal or run this command:

Import-Module "$env:ChocolateyInstall\helpers\chocolateyInstaller.psm1" ; Update-SessionEnvironment

Now you can use Chocolatey to install Python (latest version of 3.x is default).

choco install python

# This next command installs the latest VisualStudio installer that lets you get specific versions of the build
# Microsoft has replaced the 2015 and 2017 installer links with this one, and we can still use it to install the 2015 and 2017 components

choco install visualstudio2019buildtools --package-parameters "--add Microsoft.VisualStudio.Component.VC.140 --passive --locale en-US --add Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build) --no-includeRecommended" -y --timeout 0

# Usually need the "unlimited" timeout aka "0" because Visual Studio Installer takes forever

# Tool portion
# Microsoft.VisualStudio.Product.BuildTools
# Component portion(s)
# Microsoft.VisualStudio.Component.VC.140
# Win10SDK needs to match your current Win10 build version
# $($PSVersionTable.BuildVersion.Build)
# Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build)

# Because VS2019 Build Tools are dumb, need to manually link a couple files between the SDK and the VC++ dirs
# You may need to tweak the version here, but it has been updated to be as dynamic as possible 
# Use an elevated Powershell or elevated cmd prompt (if using cmd.exe just use the bits after /c)
cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rc.exe" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rc.exe"

cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rcdll.dll" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rcdll.dll"

Once you have this installed, you should reboot. I've occasionally had things work without a reboot, but your pip install commands will work best if you reboot first.

Now you can pip install pipenv or pip install complex-package and should be good to go.

How to sort a List<Object> alphabetically using Object name field

This is assuming a list of YourClass instead of Object, as explained by amit.

You can use this bit from the Google Guava library:

Collections.sort(list, Ordering.natural()
  .onResultOf(new Function<String,YourClass>() {
  public String call(YourClass o) {
     return o.getName();
  }))
  .nullsLast();

The other answers which mention Comparator are not incorrect, since Ordering implements Comparator. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".

Copied shamelessly from this answer on my own question.

iOS: UIButton resize according to text length

For some reason, func sizeToFit() does not work for me. My set up is I am using a button inside a UITableViewCell and I am using auto layout.

What worked for me is:

  1. get the width constraint
  2. get the intrinsicContentSize width because according the this document auto layout is not aware of the intrinsicContentSize. Set the width constraint to the intrinsicContentSize width

enter image description here

Here're two titles from the Debug View Hierachry enter image description here

enter image description here

Dart SDK is not configured

After installing Flutter, the best way to install Dart sdk is by creating a new project. In this window, click INSTALL SDK. This installs all necessary to work properly.

How can I create a Java method that accepts a variable number of arguments?

You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

Using Composer's Autoload

The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.

{
    "config": {
        "vendor-dir": "../vendor/"
    },
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

Or isn't this possible in your project?

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

In the first plate you have to check that:

  • 1) You install a appropriate version of Crystal Reports SDK => http://downloads.i-theses.com/index.php?option=com_downloads&task=downloads&groupid=9&id=101 (for example)
  • 2) Add reference to dll => crystaldecisions.reportappserver.commlayer.dll

sprintf like functionality in Python

Use the formatting operator % : buf = "A = %d\n , B= %s\n" % (a, b) print >>f, buf

event Action<> vs event EventHandler<>

Looking at Standard .NET event patterns we find

The standard signature for a .NET event delegate is:

void OnEventRaised(object sender, EventArgs args);

[...]

The argument list contains two arguments: the sender, and the event arguments. The compile time type of sender is System.Object, even though you likely know a more derived type that would always be correct. By convention, use object.

Below on same page we find an example of the typical event definition which is something like

public event EventHandler<EventArgs> EventName;

Had we defined

class MyClass
{
  public event Action<MyClass, EventArgs> EventName;
}

the handler could have been

void OnEventRaised(MyClass sender, EventArgs args);

where sender has the correct (more derived) type.

How to reset AUTO_INCREMENT in MySQL?

The best solution that worked for me:

ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED;
COMMIT;
ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED AUTO_INCREMENT;
COMMIT;

Its fast, works with innoDB, and I don't need to know the current maximum value! This way the auto increment counter will reset and it will start automatically from the maximum value exists.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

This worked for me:

  1. Right click .git folder
  2. click get info
  3. set permission to your user
  4. click the Cog icon and click apply to enclosed items

No more permission denied errors in git.

Xcode project not showing list of simulators

Try This, It worked like a charm! for me,

Follow below step

1) Clean Derived Data as show below,

 rm -rf ~/Library/Developer/Xcode/DerivedData/

OR

 Xcode---> Preferences--->Location--->Derived Data

Derived Data

2) In Deployment Info change Deployment Target

It's equal to or less then the SDK version of Xcode

enter image description here

3) Quit Xcode

enter image description here

4) Reopen Xcode you will see list of simulators

enter image description here

Hope this answer will help for someone.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

I had this in VS 2012 where the "Section name" had been changed in a project, and I fixed it by deleting "app.config" in the project, then right-clicking on the project in the "Solution Explorer", selecting "Properties", then "Settings", then making a change to one of the settings, saving, and re-building. This created a new app.config with the correct information.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

Method List in Visual Studio Code

CTRL+F12 (CMD+F12 for Mac) - opens for me all methods and members in PHP class.

How to pass a textbox value from view to a controller in MVC 4?

You can use simple form:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

File opens instead of downloading in internet explorer in a href link

Zip your file (.zip) and IE will give the user the option to open or download the file.

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

Change the color of a bullet in a html list?

Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.

How to find all positions of the maximum value in a list?

I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:

=== maxelements.py ===

a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c

def maxelements_s(seq): # @SilentGhost
    ''' Return list of position(s) of largest element '''
    m = max(seq)
    return [i for i, j in enumerate(seq) if j == m]

def maxelements_m(seq): # @martineau
    ''' Return list of position(s) of largest element '''
    max_indices = []
    if len(seq):
        max_val = seq[0]
        for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
            if val == max_val:
                max_indices.append(i)
            else:
                max_val = val
                max_indices = [i]
    return max_indices

def maxelements_j(seq): # @John Machin
    ''' Return list of position(s) of largest element '''
    if not seq: return []
    max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
    max_indices = []
    for i, val in enumerate(seq):
        if val < max_val: continue
        if val == max_val:
            max_indices.append(i)
        else:
            max_val = val
            max_indices = [i]
    return max_indices

Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop

difference between width auto and width 100 percent

Width auto

The initial width of a block level element like div or p is auto. This makes it expand to occupy all available horizontal space within its containing block. If it has any horizontal padding or border, the widths of those do not add to the total width of the element.

Width 100%

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border (unless you’ve used box-sizing:border-box, in which case only margins are added to the 100% to change how its total width is calculated). This may be what you want, but most likely it isn’t.

To visualise the difference see this picture:

enter image description here

Source

GZIPInputStream reading line by line

BufferedReader in = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));

String content;

while ((content = in.readLine()) != null)

   System.out.println(content);

ERROR 1044 (42000): Access denied for 'root' With All Privileges

First, Identify the user you are logged in as:

 select user();
 select current_user();

The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost in mysql.

Grant_priv to root@localhost. Here is how you can check.

mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host      | user             | password                                  | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root             | ***************************************** | N          | Y          |
| localhost | debian-sys-maint | ***************************************** | Y          | Y          |
| localhost | staging          | ***************************************** | N          | N          |
+-----------+------------------+-------------------------------------------+------------+------------+

You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';

I logged back in, it was fine.

Access Google's Traffic Data through a Web Service

Apparently the information is available using the Google Directions API in its professional edition Maps for work. According to the API's documentation:

Note: Maps for Work users must include client and signature parameters with their requests instead of a key.
[...]
duration_in_traffic indicates the total duration of this leg, taking into account current traffic conditions. The duration in traffic will only be returned if all of the following are true:

  • The directions request includes a departure_time parameter set to a value within a few minutes of the current time.
  • The request includes a valid Google Maps API for Work client and signature parameter.
  • Traffic conditions are available for the requested route.
  • The directions request does not include stopover waypoints.

Synchronizing a local Git repository with a remote one

The permanent fix if one wants to create a new branch on the remote to mirror and track your local branch(or, vice-versa) is:

git config --global push.default current

I always configure my local git with this command after I do git clone. Although it can be applied anytime when the local-remote branch "Git fatal: The current branch has no upstream branch" error occurs.

Hope this helps. Much peace. :)

Best way to repeat a character in C#

Albeit very similar to a previous suggestion, I like to keep it simple and apply the following:

string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");

Standard .Net really,

Java generics - why is "extends T" allowed but not "implements T"?

The answer is in here :

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean either extends (as in classes) or implements (as in interfaces).

So there you have it, it's a bit confusing, and Oracle knows it.

How to dump a table to console?

The simplest way, with circular reference handling and all:

function dump(t, indent, done)
    done = done or {}
    indent = indent or 0

    done[t] = true

    for key, value in pairs(t) do
        print(string.rep("\t", indent))

        if (type(value) == "table" and not done[value]) then
            done[value] = true
            print(key, ":\n")

            dump(value, indent + 2, done)
            done[value] = nil
        else
            print(key, "\t=\t", value, "\n")
        end
    end
end

Jquery DatePicker Set default date

For today's Date

$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

How to get a function name as a string?

I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:

class EnterExitLog():
    def __init__(self, funcName):
        self.funcName = funcName

    def __enter__(self):
        gLog.debug('Started: %s' % self.funcName)
        self.init_time = datetime.datetime.now()
        return self

    def __exit__(self, type, value, tb):
        gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))

def func_timer_decorator(func):
    def func_wrapper(*args, **kwargs):
        with EnterExitLog(func.__name__):
            return func(*args, **kwargs)

    return func_wrapper

so now all you have to do with your function is decorate it and voila

@func_timer_decorator
def my_func():

How to open an external file from HTML

Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='http://server/directory/file.xlsx'

Omitting one Setter/Getter in Lombok

User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter and @Setter.

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;

Spring boot 2.3 version, this is working well.

Difference between text and varchar (character varying)

As "Character Types" in the documentation points out, varchar(n), char(n), and text are all stored the same way. The only difference is extra cycles are needed to check the length, if one is given, and the extra space and time required if padding is needed for char(n).

However, when you only need to store a single character, there is a slight performance advantage to using the special type "char" (keep the double-quotes — they're part of the type name). You get faster access to the field, and there is no overhead to store the length.

I just made a table of 1,000,000 random "char" chosen from the lower-case alphabet. A query to get a frequency distribution (select count(*), field ... group by field) takes about 650 milliseconds, vs about 760 on the same data using a text field.

Format cell color based on value in another sheet and cell

I'm using Excel 2003 -

The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.

You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.

You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

denied: requested access to the resource is denied : docker

I also encountered this error message, using the Gitlab registry. The difference was that I was attempting to change the name of the image from previous builds. The problem there, is that the registry for the image being pushed did not exist, because the new name of the image didn't match any of the projects in my group.

TLDR: In Gitlab, the image name has to match the project name.

Easy way to test a URL for 404 in PHP?

If you are looking for an easiest solution and the one you can try in one go on php5 do

file_get_contents('www.yoursite.com');
//and check by echoing
echo $http_response_header[0];

Best GUI designer for eclipse?

Look at my plugin for developing swing application. It is as easy as that of netbeans': http://code.google.com/p/visualswing4eclipse/

how to convert java string to Date object

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".

So, try to change the code to:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

Output:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

What's the simplest way of detecting keyboard input in a script from the terminal?

Edit:

I've thought about this problem a lot, and there are a few different behaviors one could want. I've been implementing most of them for Unix and Windows, and will post them here once they are done.

Synchronous/Blocking key capture:

  1. A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.
  2. A simple blocking function that waits for the user to press a single key, then returns that key

Asynchronous key capture:

  1. A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)
  2. A callback that is called with the typed text after the user presses enter (a less realtime keylogger)
  3. A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Polling:

  1. The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

  2. The same as 1, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Implementations

Synchronous/Blocking key capture:

A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.

typedString = raw_input()

A simple blocking function that waits for the user to press a single key, then returns that key

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        import Carbon
        Carbon.Evt #see if it has this (in Unix, it doesn't)

    def __call__(self):
        import Carbon
        if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break

    return k

Asynchronous key capture:

A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)

A callback that is called with the typed text after the user presses enter (a less realtime keylogger)

Windows:

This uses the windows Robot given below, naming the script keyPress.py

# Some if this is from http://nullege.com/codes/show/src@e@i@einstein-HEAD@Python25Einstein@[email protected]/380/win32api.GetStdHandle
# and
# http://nullege.com/codes/show/src@v@i@VistA-HEAD@Python@[email protected]/901/win32console.GetStdHandle.PeekConsoleInput

from ctypes import *
import time
import threading

from win32api import STD_INPUT_HANDLE, STD_OUTPUT_HANDLE

from win32console import GetStdHandle, KEY_EVENT, ENABLE_WINDOW_INPUT, ENABLE_MOUSE_INPUT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT

import keyPress


class CaptureLines():
    def __init__(self):
        self.stopLock = threading.Lock()

        self.isCapturingInputLines = False

        self.inputLinesHookCallback = CFUNCTYPE(c_int)(self.inputLinesHook)
        self.pyosInputHookPointer = c_void_p.in_dll(pythonapi, "PyOS_InputHook")
        self.originalPyOsInputHookPointerValue = self.pyosInputHookPointer.value

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

    def inputLinesHook(self):

        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
        inputChars = self.readHandle.ReadConsole(10000000)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)

        if inputChars == "\r\n":
            keyPress.KeyPress("\n")
            return 0

        inputChars = inputChars[:-2]

        inputChars += "\n"

        for c in inputChars:
            keyPress.KeyPress(c)

        self.inputCallback(inputChars)

        return 0


    def startCapture(self, inputCallback):
        self.stopLock.acquire()

        try:
            if self.isCapturingInputLines:
                raise Exception("Already capturing keystrokes")

            self.isCapturingInputLines = True
            self.inputCallback = inputCallback

            self.pyosInputHookPointer.value = cast(self.inputLinesHookCallback, c_void_p).value
        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

    def stopCapture(self):
        self.stopLock.acquire()

        try:
            if not self.isCapturingInputLines:
                raise Exception("Keystrokes already aren't being captured")

            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.isCapturingInputLines = False
            self.pyosInputHookPointer.value = self.originalPyOsInputHookPointerValue

        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Windows:

import threading
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT


class KeyAsyncReader():
    def __init__(self):
        self.stopLock = threading.Lock()
        self.stopped = True
        self.capturedChars = ""

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)



    def startReading(self, readCallback):
        self.stopLock.acquire()

        try:
            if not self.stopped:
                raise Exception("Capture is already going")

            self.stopped = False
            self.readCallback = readCallback

            backgroundCaptureThread = threading.Thread(target=self.backgroundThreadReading)
            backgroundCaptureThread.daemon = True
            backgroundCaptureThread.start()
        except:
            self.stopLock.release()
            raise

        self.stopLock.release()


    def backgroundThreadReading(self):
        curEventLength = 0
        curKeysLength = 0
        while True:
            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            self.stopLock.acquire()
            if self.stopped:
                self.stopLock.release()
                return
            self.stopLock.release()


            if len(eventsPeek) == 0:
                continue

            if not len(eventsPeek) == curEventLength:
                if self.getCharsFromEvents(eventsPeek[curEventLength:]):
                    self.stopLock.acquire()
                    self.stopped = True
                    self.stopLock.release()
                    break

                curEventLength = len(eventsPeek)



    def getCharsFromEvents(self, eventsPeek):
        callbackReturnedTrue = False
        for curEvent in eventsPeek:
            if curEvent.EventType == KEY_EVENT:
                    if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                        pass
                    else:
                        curChar = str(curEvent.Char)
                        if self.readCallback(curChar) == True:
                            callbackReturnedTrue = True


        return callbackReturnedTrue

    def stopReading(self):
        self.stopLock.acquire()
        self.stopped = True
        self.stopLock.release()

Polling:

The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

Windows and OS X (and maybe Linux):

global isWindows

isWindows = False
try:
    from win32api import STD_INPUT_HANDLE
    from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
    isWindows = True
except ImportError as e:
    import sys
    import select
    import termios


class KeyPoller():
    def __enter__(self):
        global isWindows
        if isWindows:
            self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.curEventLength = 0
            self.curKeysLength = 0

            self.capturedChars = []
        else:
            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

        return self

    def __exit__(self, type, value, traceback):
        if isWindows:
            pass
        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)

    def poll(self):
        if isWindows:
            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)

            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            if len(eventsPeek) == 0:
                return None

            if not len(eventsPeek) == self.curEventLength:
                for curEvent in eventsPeek[self.curEventLength:]:
                    if curEvent.EventType == KEY_EVENT:
                        if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                            pass
                        else:
                            curChar = str(curEvent.Char)
                            self.capturedChars.append(curChar)
                self.curEventLength = len(eventsPeek)

            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)
            else:
                return None
        else:
            dr,dw,de = select.select([sys.stdin], [], [], 0)
            if not dr == []:
                return sys.stdin.read(1)
            return None

Simple use case:

with KeyPoller() as keyPoller:
    while True:
        c = keyPoller.poll()
        if not c is None:
            if c == "c":
                break
            print c

The same as above, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Windows:

# Modified from http://stackoverflow.com/a/13615802/2924421

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM

SendInput = ctypes.windll.user32.SendInput

PUL = ctypes.POINTER(ctypes.c_ulong)

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

def KeyDown(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyUp(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    extra = ctypes.c_ulong(0)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag | KEYEVENTF_KEYUP, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyPress(unicodeKey):
    time.sleep(0.0001)
    KeyDown(unicodeKey)
    time.sleep(0.0001)
    KeyUp(unicodeKey)
    time.sleep(0.0001)


def GetKeyCode(unicodeKey):
    k = unicodeKey
    curKeyCode = 0
    if k == "up": curKeyCode = 0x26
    elif k == "down": curKeyCode = 0x28
    elif k == "left": curKeyCode = 0x25
    elif k == "right": curKeyCode = 0x27
    elif k == "home": curKeyCode = 0x24
    elif k == "end": curKeyCode = 0x23
    elif k == "insert": curKeyCode = 0x2D
    elif k == "pgup": curKeyCode = 0x21
    elif k == "pgdn": curKeyCode = 0x22
    elif k == "delete": curKeyCode = 0x2E
    elif k == "\n": curKeyCode = 0x0D

    if curKeyCode == 0:
        return 0, int(unicodeKey.encode("hex"), 16), KEYEVENTF_UNICODE
    else:
        return curKeyCode, 0, 0

OS X:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

Missing maven .m2 folder

Is there some command to create this folder?

If smb face this issue again, you should know the most simple way to create .m2 folder.
If you unzipped maven and set up maven path variable - just try mvn clean command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.

How do I return multiple values from a function in C?

By passing parameters by reference to function.

Examples:

 void incInt(int *y)
 {
     (*y)++;  // Increase the value of 'x', in main, by one.
 }

Also by using global variables but it is not recommended.

Example:

int a=0;

void main(void)
{
    //Anything you want to code.
}

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

How to save final model using keras?

you can save the model and load in this way.

from keras.models import Sequential, load_model
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss':crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

Make a negative number positive

I needed the absolute value of a long , and looked deeply into Math.abs and found that if my argument is less than LONG.MIN_VAL which is -9223372036854775808l, then the abs function would not return an absolute value but only the minimum value. Inthis case if your code is using this abs value further then there might be an issue.

#pragma pack effect

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:

struct Test
{
   char AA;
   int BB;
   char CC;
};

The compiler could choose to lay the struct out in memory like this:

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) | 
| CC(1) | pad.................. |

and sizeof(Test) would be 4 × 3 = 12, even though it only contains 6 bytes of data. The most common use case for the #pragma (to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1), the struct above would be laid out like this:

|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |

And sizeof(Test) would be 1 × 6 = 6.

With #pragma pack(2), the struct above would be laid out like this:

|   1   |   2   | 

| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |

And sizeof(Test) would be 2 × 4 = 8.

Order of variables in struct is also important. With variables ordered like following:

struct Test
{
   char AA;
   char CC;
   int BB;
};

and with #pragma pack(2), the struct would be laid out like this:

|   1   |   2   | 

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |

and sizeOf(Test) would be 3 × 2 = 6.

Best way to specify whitespace in a String.Split operation

If you just call:

string[] ssize = myStr.Split(null); //Or myStr.Split()

or:

string[] ssize = myStr.Split(new char[0]);

then white-space is assumed to be the splitting character. From the string.Split(char[]) method's documentation page.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Always, always, always read the documentation!

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

How to determine the version of Gradle?

I running the following in my project:

./gradlew --version

------------------------------------------------------------
Gradle 4.7
------------------------------------------------------------

Build time:   2018-04-18 09:09:12 UTC
Revision:     b9a962bf70638332300e7f810689cb2febbd4a6c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_212 (AdoptOpenJDK 25.212-b03)
OS:           Mac OS X 10.15 x86_64

Express: How to pass app-instance to routes from a different file?

Use req.app, req.app.get('somekey')

The application variable created by calling express() is set on the request and response objects.

See: https://github.com/visionmedia/express/blob/76147c78a15904d4e4e469095a29d1bec9775ab6/lib/express.js#L34-L35

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

Is there a way to perform "if" in python's lambda

You can also use Logical Operators to have something like a Conditional

func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse

You can see more about Logical Operators here

PHP: Get key from array?

$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}

Program to find prime numbers

You only need to check odd divisors up to the square root of the number. In other words your inner loop needs to start:

for (int j = 3; j <= Math.Sqrt(i); j+=2) { ... }

You can also break out of the function as soon as you find the number is not prime, you don't need to check any more divisors (I see you're already doing that!).

This will only work if num is bigger than two.

No Sqrt

You can avoid the Sqrt altogether by keeping a running sum. For example:

int square_sum=1;
for (int j=3; square_sum<i; square_sum+=4*(j++-1)) {...}

This is because the sum of numbers 1+(3+5)+(7+9) will give you a sequence of odd squares (1,9,25 etc). And hence j represents the square root of square_sum. As long as square_sum is less than i then j is less than the square root.

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

What are the differences between struct and class in C++?

Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.

SQL Server check case-sensitivity?

SQL Server is not case sensitive. SELECT * FROM SomeTable is the same as SeLeCT * frOM soMetaBLe.

SQL count rows in a table

Use This Query :

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

PHP decoding and encoding json with unicode characters

Judging from everything you've said, it seems like the original Odómetro string you're dealing with is encoded with ISO 8859-1, not UTF-8.

Here's why I think so:

  • json_encode produced parseable output after you ran the input string through utf8_encode, which converts from ISO 8859-1 to UTF-8.
  • You did say that you got "mangled" output when using print_r after doing utf8_encode, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3 in UTF-8, but that sequence is ó in ISO 8859-1.
  • Your htmlentities hackaround solution worked. htmlentities needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)
  • You said you had the same problem in Python, which would seem to exclude PHP from being the issue.

PHP will use the \uXXXX escaping, but as you noted, this is valid JSON.

So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8' to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode, but this will only support characters that are part of ISO 8859-1).

Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r testing).

html select only one checkbox in a group

My version: use data attributes and Vanilla JavaScript

<div class="test-checkbox">
    Group One: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
    <br />
    Group Two: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
</div>
<script>
    let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
    [...cbxes].forEach((cbx) => {
        cbx.addEventListener('change', (e) => {
            if (e.target.checked)
                uncheckOthers(e.target);
        });
    });
    function uncheckOthers (clicked) {
        let name = clicked.getAttribute('name');
        // find others in same group, uncheck them
        [...cbxes].forEach((other) => {
            if (other != clicked && other.getAttribute('name') == name)
                other.checked = false;
        });
    }
</script>

How can I add or update a query string parameter?

Java script code to find a specific query string and replace its value *

('input.letter').click(function () {
                //0- prepare values
                var qsTargeted = 'letter=' + this.value; //"letter=A";
                var windowUrl = '';
                var qskey = qsTargeted.split('=')[0];
                var qsvalue = qsTargeted.split('=')[1];
                //1- get row url
                var originalURL = window.location.href;
                //2- get query string part, and url
                if (originalURL.split('?').length > 1) //qs is exists
                {
                    windowUrl = originalURL.split('?')[0];
                    var qs = originalURL.split('?')[1];
                    //3- get list of query strings
                    var qsArray = qs.split('&');
                    var flag = false;
                    //4- try to find query string key
                    for (var i = 0; i < qsArray.length; i++) {
                        if (qsArray[i].split('=').length > 0) {
                            if (qskey == qsArray[i].split('=')[0]) {
                                //exists key
                                qsArray[i] = qskey + '=' + qsvalue;
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)//   //5- if exists modify,else add
                    {
                        qsArray.push(qsTargeted);
                    }
                    var finalQs = qsArray.join('&');
                    //6- prepare final url
                    window.location = windowUrl + '?' + finalQs;
                }
                else {
                    //6- prepare final url
                    //add query string
                    window.location = originalURL + '?' + qsTargeted;
                }
            })
        });

How to make an executable JAR file?

It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.

First of all make sure to download and add maven to path. [ mvn --version ] will give you version specifications of it if you have added to the path correctly.

Now , add following code to the maven project [ pom.xml ] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].

      <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                    <mainClass>
            your_package_to_class_that_contains_main_file .MainFileName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Now go to the command line [CMD] in your project and type mvn package and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar under target directory.

Now navigate to the target directory by cd target.

Finally type java -jar jar-file-name.jar and yes this should work successfully if you don't have any errors in your program.

Python: convert string from UTF-8 to Latin-1

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

Get size of folder or file

Here's the best way to get a general File's size (works for directory and non-directory):

public static long getSize(File file) {
    long size;
    if (file.isDirectory()) {
        size = 0;
        for (File child : file.listFiles()) {
            size += getSize(child);
        }
    } else {
        size = file.length();
    }
    return size;
}

Edit: Note that this is probably going to be a time-consuming operation. Don't run it on the UI thread.

Also, here (taken from https://stackoverflow.com/a/5599842/1696171) is a nice way to get a user-readable String from the long returned:

public static String getReadableSize(long size) {
    if(size <= 0) return "0";
    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups))
            + " " + units[digitGroups];
}

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

I had the exact same issue. The following thread helped me solve it. Just set your Compile SDK version to Android P.

https://stackoverflow.com/a/49172361/1542720

I fixed this issue by selecting:

API 27+: Android API 27, P preview (Preview)

in the project structure settings. the following image shows my settings. The 13 errors that were coming while building the app, have disappeared.

Gradle settings

Arduino COM port doesn't work

Did you install the drivers? See the Arduino installation instructions under #4. I don't know that machine but I doubt it doesn't have any COM ports.

React-Native: Application has not been registered error

After have read all the above, I have found that there could be another reason for this.

In my case:

react-native-cli: 2.0.1

react-native: 0.60.4

and following structure:

enter image description here

First has to be noted that index.android is not been update in Android Studio when the build run by Metro builder( react-native run-android) so it has to be done manually. Also in Android studio does not "read" the

app.json(created by default together with index.js, that renamed index.android.js):

 {
    "name": "authApp",
    "displayName": "authApp"
 }

and so this like

(in my case)

import {authApp as appName} from './app.json';

cause the fact that android studio does not know what authApp refer to. I fix for the moment referring to the app name with its string name and not using that import from app.json:

AppRegistry.registerComponent('authApp', () => MyApp);

Removing numbers from string

If i understand your question right, one way to do is break down the string in chars and then check each char in that string using a loop whether it's a string or a number and then if string save it in a variable and then once the loop is finished, display that to the user

Get specific objects from ArrayList when objects were added anonymously?

You could use list.indexOf(Object) bug in all honesty what you're describing sounds like you'd be better off using a Map.

Try this:

Map<String, Object> mapOfObjects = new HashMap<String, Object>();
mapOfObjects.put("objectName", object);

Then later when you want to retrieve the object, use

mapOfObjects.get("objectName");

Assuming you do know the object's name as you stated, this will be both cleaner and will have faster performance besides, particularly if the map contains large numbers of objects.

If you need the objects in the Map to stay in order, you can use

Map<String, Object> mapOfObjects = new LinkedHashMap<String, Object>();

instead

What is the best way to get all the divisors of a number?

My solution via generator function is:

def divisor(num):
    for x in range(1, num + 1):
        if num % x == 0:
            yield x
    while True:
        yield None

How to determine if .NET Core is installed

On windows, You only need to open the command prompt and type:

dotnet --version

If the .net core framework installed you will get current installed version

see screenshot:

enter image description here

How can I convert an RGB image into grayscale in Python?

I came to this question via Google, searching for a way to convert an already loaded image to grayscale.

Here is a way to do it with SciPy:

import scipy.misc
import scipy.ndimage

# Load an example image
# Use scipy.ndimage.imread(file_name, mode='L') if you have your own
img = scipy.misc.face()

# Convert the image
R = img[:, :, 0]
G = img[:, :, 1]
B = img[:, :, 2]
img_gray = R * 299. / 1000 + G * 587. / 1000 + B * 114. / 1000

# Show the image
scipy.misc.imshow(img_gray)

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

How do you create an asynchronous method in C#?

I don't recommend StartNew unless you need that level of complexity.

If your async method is dependent on other async methods, the easiest approach is to use the async keyword:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  for (int i = 0; i < num; i++)
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }

  return DateTime.Now;
}

If your async method is doing CPU work, you should use Task.Run:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  await Task.Run(() => ...);
  return DateTime.Now;
}

You may find my async/await intro helpful.

How to display alt text for an image in chrome

You can use the title attribute.

<img height="90" width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif"
alt="Google Images" title="Google Images" />

What's the difference between an element and a node in XML?

A node can be a number of different kinds of things: some text, a comment, an element, an entity, etc. An element is a particular kind of node.

Maven dependencies are failing with a 501 error

If you are using Netbeans older version, you have to make changes in maven to use https over http

Open C:\Program Files\NetBeans8.0.2\java\maven\conf\settings.xml and paste below code in between mirrors tag

<mirror>
<id>maven-mirror</id>
<name>Maven Mirror</name>
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>

It will force maven to use https://repo.maven.apache.org/maven2 url.

How to make a countdown timer in Android?

Using Kotlin:

var timer = object: CountDownTimer(30000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tvTimer.setText("seconds remaining: " + millisUntilFinished / 1000)
        }

        override fun onFinish() {
            tvTimer.setText("done!")
        }
    }
timer.start()

Is there a command to refresh environment variables from the command prompt in Windows?

Edit: this only works if the environment changes you're doing are as a result of running a batch file.

If a batch file begins with SETLOCAL then it will always unravel back to your original environment on exit even if you forget to call ENDLOCAL before the batch exits, or if it aborts unexpectedly.

Almost every batch file I write begins with SETLOCAL since in most cases I don't want the side-effects of environment changes to remain. In cases where I do want certain environment variable changes to propagate outside the batch file then my last ENDLOCAL looks like this:

ENDLOCAL & (
  SET RESULT1=%RESULT1%
  SET RESULT2=%RESULT2%
)

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

A simple scenario using wait() and notify() in java

Example

public class myThread extends Thread{
     @override
     public void run(){
        while(true){
           threadCondWait();// Circle waiting...
           //bla bla bla bla
        }
     }
     public synchronized void threadCondWait(){
        while(myCondition){
           wait();//Comminucate with notify()
        }
     }

}
public class myAnotherThread extends Thread{
     @override
     public void run(){
        //Bla Bla bla
        notify();//Trigger wait() Next Step
     }

}

How do I execute a PowerShell script automatically using Windows task scheduler?

Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely and up:

# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely

# Options
$option1 = New-ScheduledJobOption –StartIfIdle

$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"

Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger  $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to check the presence of php and apache on ubuntu server through ssh

Try this.

dpkg -s apache2 | grep Status 

dpkg -s php5 | grep Status

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Python decorators in classes

This is one way to access(and have used) self from inside a decorator defined inside the same class:

class Thing(object):
    def __init__(self, name):
        self.name = name

    def debug_name(function):
        def debug_wrapper(*args):
            self = args[0]
            print 'self.name = ' + self.name
            print 'running function {}()'.format(function.__name__)
            function(*args)
            print 'self.name = ' + self.name
        return debug_wrapper

    @debug_name
    def set_name(self, new_name):
        self.name = new_name

Output (tested on Python 2.7.10):

>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'

The example above is silly, but it works.

How to remove text from a string?

Using match() and Number() to return a number variable:

Number(("data-123").match(/\d+$/));

// strNum = 123

Here's what the statement above does...working middle-out:

  1. str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
  2. Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.

Post-increment and Pre-increment concept?

Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.

_x000D_
_x000D_
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
_x000D_
_x000D_

Declare an array in TypeScript

Specific type of array in typescript

export class RegisterFormComponent 
{
     genders = new Array<GenderType>();   // Use any array supports different kind objects

     loadGenders()
     {
        this.genders.push({name: "Male",isoCode: 1});
        this.genders.push({name: "FeMale",isoCode: 2});
     }
}

type GenderType = { name: string, isoCode: number };    // Specified format

Change old commit message on Git

Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.

Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.

So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.

From latest master:

git checkout -b new-branch

Then

git merge --squash problem-branch
git commit -m "new message" 

Referece: https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch

Better way to check if a Path is a File or a Directory?

With only this line you can get if a path is a directory or a file:

File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)

Auto-expanding layout with Qt-Designer

Once you have add your layout with at least one widget in it, select your window and click the "Update" button of QtDesigner. The interface will be resized at the most optimized size and your layout will fit the whole window. Then when resizing the window, the layout will be resized in the same way.

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

How to len(generator())

You can use send as a hack:

def counter():
    length = 10
    i = 0
    while i < length:
        val = (yield i)
        if val == 'length':
            yield length
        i += 1

it = counter()
print(it.next())
#0
print(it.next())
#1
print(it.send('length'))
#10
print(it.next())
#2
print(it.next())
#3

sweet-alert display HTML code in text

All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true ,

    var hh = "<b>test</b>"; 
swal({
        title: "" + txt + "", 
        text: "Testno  sporocilo za objekt " + hh + "",  
        html: true,  
        confirmButtonText: "V redu", 
        allowOutsideClick: "true"  
});

Note: html : "Testno sporocilo za objekt " + hh + "",
may not work as html porperty is only use to active this feature by assign true / false value in the Sweetalert.
this html : "Testno sporocilo za objekt " + hh + "", is used in SweetAlert2

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Open a facebook link by native Facebook app on iOS

This will open the URL in Safari:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];

For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Stolen from the above site:

fb://profile – Open Facebook app to the user’s profile
fb://friends – Open Facebook app to the friends list
fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
fb://feed – Open Facebook app to the News Feed
fb://events – Open Facebook app to the Events page
fb://requests – Open Facebook app to the Requests list
fb://notes - Open Facebook app to the Notes page
fb://albums – Open Facebook app to Photo Albums list

To launch the above URLs:

NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
[[UIApplication sharedApplication] openURL:theURL];

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

You can use the simple program StarUML. The trial version is unlimited and can do almost anything.

Onced installed you can use it to generate great number of uml digrams just by pasting the source code. Class diagram is just one type of it. (It understands not only Java language but C#, C++ and other)

P.S. The program is great for drawing architectural diagrams before you start to code the program.

Passing arguments to AsyncTask, and returning results

I dont do it like this. I find it easier to overload the constructor of the asychtask class ..

public class calc_stanica extends AsyncTask>

String String mWhateveryouwantToPass;

 public calc_stanica( String whateveryouwantToPass)
{

    this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use  whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/   ...  ...  

Are the shift operators (<<, >>) arithmetic or logical in C?

When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.

(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)

When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.

For example, assuming a 32 bit machine:

signed int x1 = 5;
assert((x1 >> 1) == 2);
signed int x2 = -5;
assert((x2 >> 1) == -3);
unsigned int x3 = (unsigned int)-5;
assert((x3 >> 1) == 0x7FFFFFFD);

The VMware Authorization Service is not running

I followed Telvin's suggestion and it worked on Windows 7:

  1. Run the VMware installer by right clicking on it and selecting "Run as Administrator"
  2. In the resulting popup menu, select "Repair installation"

SQLite add Primary Key

sqlite>  create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t values(1, 'he', 'ha');
sqlite>
sqlite>  create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));

How do I create a slug in Django?

If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False. Otherwise you'll get an error when trying to save in Admin.

So a modification to the above example would be::

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()

Determine a user's timezone

Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside.

Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability.

IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct.

Exit a while loop in VBS/VBA

I know this is old as dirt but it ranked pretty high in google.

The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks

In the example given

num = 0
While num < 10
  If status = "Fail" Then
    num = 10
  End If
  num = num + 1
Wend

After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.

Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:

num = 0
While num < 10
  If folder = "System32" Then
    num = 10
  End If
  RecursiveDeleteFunction folder
  num = num + 1
Wend

Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

How to remove youtube branding after embedding video in web page?

You can add ?modestbranding=1 to your url. That will remove the logo.

modestbranding (supported players: AS3, HTML5)

This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar. Note that a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player.

&showinfo=0 will remove the title bar.

showinfo (supported players: AS3, AS2, HTML5)

Values: 0 or 1. The parameter's default value is 1. If you set the parameter value to 0, then the player will not display information like the video title and uploader before the video starts playing.

You can find all options on the Google Developers website.

Note:

It doesn't fully remove the logo. There is still a small logo on the bottom left.

showinfo is deprecated and will be ignored after September 25, 2018: https://developers.google.com/youtube/player_parameters

iPhone: How to get current milliseconds?

Try this :

NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];

NSString *newDateString = [dateFormatter stringFromDate:timestamp];
timestamp = (NSDate*)newDateString;

In this example, dateWithTimeIntervalSince1970 is used in combination of the formatter @"YYYY-MM-dd HH:mm:ss.SSS" that will return the date with year, month, day and the time with hours, minutes, seconds, and milliseconds. See the example : "2015-12-02 04:43:15.008". I used the NSString to be sure that the format will be has written before.

How to start mongodb shell?

In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:

$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>

Once you get > symbol in the terminal, you have entered into the MongoDB shell.

Storing image in database directly or as base64 data?

I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

jQuery Validate Plugin - Trigger validation of single field

$("#FormId").validate().element('#FieldId');

How much should a function trust another function

If it is in the same class it is fine to trust the method.

It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.

It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.

How to make function decorators and chain them together?

To explain the decorator in a simple way:

With:

@decor1
@decor2
def func(*args, **kwargs):
    pass

When do:

func(*args, **kwargs)

You really do:

decor1(decor2(func))(*args, **kwargs)

No == operator found while comparing structs in C++

Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

How to reset sequence in postgres and fill id column with new data?

If you are using pgAdmin3, expand 'Sequences,' right click on a sequence, go to 'Properties,' and in the 'Definition' tab change 'Current value' to whatever value you want. There is no need for a query.

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

Display / print all rows of a tibble (tbl_df)

I prefer to turn the tibble to data.frame. It shows everything and you're done

df %>% data.frame 

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

Add inline style using Javascript

You can do it directly on the style:

var nFilter = document.createElement('div');
nFilter.className = 'well';
nFilter.innerHTML = '<label>'+sSearchStr+'</label>';

// Css styling
nFilter.style.width = "330px";
nFilter.style.float = "left";

// or
nFilter.setAttribute("style", "width:330px;float:left;");

How to convert characters to HTML entities using plain JavaScript

Best solution is posted at phpjs.org implementation of PHP function htmlentities

The format is htmlentities(string, quote_style, charset, double_encode) Full documentation on the PHP function which is identical can be read here

Ajax post request in laravel 5 return error 500 (Internal Server Error)

Short and Simple Solution

e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
/* the route pointing to the post function */
    url: url,
    type: 'DELETE',
/* send the csrf-token and the input to the controller */
    data: {message:value},
    dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
    success: function (data) { 
    console.log(data)
    //$('.writeinfo').append(data.msg);
    //$('#ruleRow'+id).remove();
    }
});
return false;

Response::json() - Laravel 5.1

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){

    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

CSS: Change image src on img:hover

What you could do is cheat a little bit by setting width and height to 0 to hide the actual image and apply some CSS to do what you want:

#aks {
    width:0px;
    height:0px;
    background:url('http://dummyimage.com/100x100/000/fff');
    padding:50px;
}

#aks:hover {
    background: url('http://dummyimage.com/100x100/eb00eb/fff');
}

And the padding making the img tag the size you want it to have (half the size of your actual image).

Fiddle

Maintain/Save/Restore scroll position when returning to a ListView

For some looking for a solution to this problem, the root of the issue may be where you are setting your list views adapter. After you set the adapter on the listview, it resets the scroll position. Just something to consider. I moved setting the adapter into my onCreateView after we grab the reference to the listview, and it solved the problem for me. =)

Error: 'int' object is not subscriptable - Python

You need to convert age1 into int first, so it can do the minus. After that turn the result back to string for display:

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
twentyone = str(21 - int(age1))
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."

Remove trailing newline from the elements of a string list

my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])

Output:

['this', 'is', 'a', 'list', 'of', 'words']

Eclipse - java.lang.ClassNotFoundException

That means your pom.xml has unresolved issues. Open the problems view solve accordingly. Then you will be able to run the test cases successfully without encountering the classnotfoundexception.

How to sort List of objects by some property

As mentioned you can sort by:

  • Making your object implement Comparable
  • Or pass a Comparator to Collections.sort

If you do both, the Comparable will be ignored and Comparator will be used. This helps that the value objects has their own logical Comparable which is most reasonable sort for your value object, while each individual use case has its own implementation.

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Listing only directories in UNIX

use this to get a list of directory

ls -d */ | sed -e "s/\///g"

Open another application from your own (intent)

Firstly, the concept of "application" in Android is slightly an extended one.

An application - technically a process - can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running (the process).

So, what you have to identify is how do you want to "start the application".

Ok... here's what you can try out:

  1. Create an intent with action=MAIN and category=LAUNCHER
  2. Get the PackageManager from the current context using context.getPackageManager
  3. packageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcher
  4. Get theActivityInfo you're interested in
  5. From the ActivityInfo, get the packageName and name
  6. Finally, create another intent with with category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  7. Finally, context.startActivity(newIntent)

Android XXHDPI resources

480 dpi is the standard QUANTIZED resolution for xxhdpi, it can vary something less (i.e.: 440 dpi) or more (i.e.: 520 dpi). Scale factor: 3x (3 * mdpi).

Now there's a higher resolution, xxxhdpi (640 dpi). Scale factor 4x (4 * mdpi).

Here's the source reference.

Getting return value from stored procedure in C#

retval.Direction = ParameterDirection.Output;

ParameterDirection.ReturnValue should be used for the "return value" of the procedure, not output parameters. It gets the value returned by the SQL RETURN statement (with the parameter named @RETURN_VALUE).

Instead of RETURN @b you should SET @b = something

By the way, return value parameter is always int, not string.

How to add Headers on RESTful call using Jersey Client API

String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

Rather than editing batch files (which you may have to do for other Ruby gems, e.g. Bundler), it's probably better to do this once, and do it properly.

On Windows, behind my corporate proxy, all I had to do was add the HTTP_PROXY environment variable to my system.

  1. Start -> right click Computer -> Properties
  2. Choose "Advanced System Settings"
  3. Click Advanced -> Environment Variables
  4. Create a new System variable named "HTTP_PROXY", and set the Value to your proxy server
  5. Reboot or log out and back in again

Depending on your authentication requirements, the HTTP_PROXY value can be as simple as:

http://proxy-server-name

Or more complex as others have pointed out

http://username:password@proxy-server-name:port-number

How to show row number in Access query like ROW_NUMBER in SQL

by VB function:

Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue

If Not m_RowNr(1) = strQName Then
  m_RowNr(0) = 1
  m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
  m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
  m_RowNr(0) = m_RowNr(0) + 1
End If

m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)

End Function

Usage(without sorting option):

SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id

if sorting required or multiple tables join then create intermediate table:

 SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
 INTO table_with_Nr
 From table A
 Order By A.id

Using Django time/date widgets in custom form

In Django 10. myproject/urls.py: at the beginning of urlpatterns

  from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
.
.
.]

In my template.html:

{% load staticfiles %}

    <script src="{% static "js/jquery-2.2.3.min.js" %}"></script>
    <script src="{% static "js/bootstrap.min.js" %}"></script>
    {# Loading internazionalization for js #}
    {% load i18n admin_modify %}
    <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/jquery.init.js" %}"></script>

    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/base.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/forms.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/login.css" %}">
    <link rel="stylesheet" type="text/css" href="{% static "/admin/css/widgets.css" %}">



    <script type="text/javascript" src="{% static "/admin/js/core.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/SelectFilter2.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/admin/RelatedObjectLookups.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/actions.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/calendar.js" %}"></script>
    <script type="text/javascript" src="{% static "/admin/js/admin/DateTimeShortcuts.js" %}"></script>

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

use MM(months) instead of mm(minutes) :

DateTime.Now.ToString("dd/MM/yyyy");

check here for more format options.

Iterate Multi-Dimensional Array with Nested Foreach Statement

Here's how to visit each element in a 2-dimensional array. Is this what you were looking for?

for (int i=0;i<array.GetLength(0);i++)
{
    for (int j=0;j<array.GetLength(1);j++)
    {
        int cell = array[i,j];
    }
}

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

View markdown files offline

You can use texts as a md viewer and md editor, its lightweight and neat. enter image description here

Android EditText view Floating Hint in Material Design

For an easier way to use the InputTextLayout, I have created this library that cuts your XML code to less than the half, and also provides you with the ability to set an error message as well as a hint message and an easy way to do your validations. https://github.com/TeleClinic/SmartEditText

Simply add

compile 'com.github.TeleClinic:SmartEditText:0.1.0'

Then you can do something like this:

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/emailSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Email"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Wrong email format"
    app:setRegexType="EMAIL_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/passwordSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Password"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setPasswordField="true"
    app:setRegexErrorMsg="Weak password"
    app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/ageSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Age"
    app:setMandatory="false"
    app:setRegexErrorMsg="Is that really your age :D?"
    app:setRegexString=".*\\d.*" />

What is the way of declaring an array in JavaScript?

In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

Using context in a fragment

The simple way is to use getActivity(). But I think the major confusion of using the getActivity() method to get the context here is a null pointer exception.

For this, first check with the isAdded() method which will determine whether it's added or not, and then we can use the getActivity() to get the context of Activity.

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

Show loading image while $.ajax is performed

  1. Create a load element for e.g. an element with id = example_load.
  2. Hide it by default by adding style="display:none;".
  3. Now show it using jquery show element function just above your ajax.

    $('#example_load').show(); $.ajax({ type: "POST", data: {}, url: '/url', success: function(){ // Now hide the load element $('#example_load').hide(); } });

CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased; is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

What exactly are DLL files, and how do they work?

Let’s say you are making an executable that uses some functions found in a library.

If the library you are using is static, the linker will copy the object code for these functions directly from the library and insert them into the executable.

Now if this executable is run it has every thing it needs, so the executable loader just loads it into memory and runs it.

If the library is dynamic the linker will not insert object code but rather it will insert a stub which basically says this function is located in this DLL at this location.

Now if this executable is run, bits of the executable are missing (i.e the stubs) so the loader goes through the executable fixing up the missing stubs. Only after all the stubs have been resolved will the executable be allowed to run.

To see this in action delete or rename the DLL and watch how the loader will report a missing DLL error when you try to run the executable.

Hence the name Dynamic Link Library, parts of the linking process is being done dynamically at run time by the executable loader.

One a final note, if you don't link to the DLL then no stubs will be inserted by the linker, but Windows still provides the GetProcAddress API that allows you to load an execute the DLL function entry point long after the executable has started.

How may I align text to the left and text to the right in the same line?

An answer using css flex layout and justify-content

_x000D_
_x000D_
p {
  display: flex;
  justify-content: space-between;
}
_x000D_
<p>
  <span>This text is left aligned</span>
  <span>This text is right aligned</span>
</p>
_x000D_
_x000D_
_x000D_

When saving, how can you check if a field has changed?

A modification to @ivanperelivskiy's answer:

@property
def _dict(self):
    ret = {}
    for field in self._meta.get_fields():
        if isinstance(field, ForeignObjectRel):
            # foreign objects might not have corresponding objects in the database.
            if hasattr(self, field.get_accessor_name()):
                ret[field.get_accessor_name()] = getattr(self, field.get_accessor_name())
            else:
                ret[field.get_accessor_name()] = None
        else:
            ret[field.attname] = getattr(self, field.attname)
    return ret

This uses django 1.10's public method get_fields instead. This makes the code more future proof, but more importantly also includes foreign keys and fields where editable=False.

For reference, here is the implementation of .fields

@cached_property
def fields(self):
    """
    Returns a list of all forward fields on the model and its parents,
    excluding ManyToManyFields.

    Private API intended only to be used by Django itself; get_fields()
    combined with filtering of field properties is the public API for
    obtaining this field list.
    """
    # For legacy reasons, the fields property should only contain forward
    # fields that are not private or with a m2m cardinality. Therefore we
    # pass these three filters as filters to the generator.
    # The third lambda is a longwinded way of checking f.related_model - we don't
    # use that property directly because related_model is a cached property,
    # and all the models may not have been loaded yet; we don't want to cache
    # the string reference to the related_model.
    def is_not_an_m2m_field(f):
        return not (f.is_relation and f.many_to_many)

    def is_not_a_generic_relation(f):
        return not (f.is_relation and f.one_to_many)

    def is_not_a_generic_foreign_key(f):
        return not (
            f.is_relation and f.many_to_one and not (hasattr(f.remote_field, 'model') and f.remote_field.model)
        )

    return make_immutable_fields_list(
        "fields",
        (f for f in self._get_fields(reverse=False)
         if is_not_an_m2m_field(f) and is_not_a_generic_relation(f) and is_not_a_generic_foreign_key(f))
    )

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I was getting this exception every time I created a "new" project.

My solution was:

  • Go menu Tools ? Extensions and Updates
  • Not check the "Updates" link...search "asp.net". There was an update to Microsoft ASP.NET and Web Tools. Get it as AspNetWebFrameworksTools2015_KB3137909.exe and install it.

That fixed it for me.


Unfortunately, I ran into another exception:

"Exception has been thrown by the target of an invocation"

I disabled the FIPS setting Enabled DWORD value to zero.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy]
Enabled=dword:00000000 And All fixed.

What happens if you don't commit a transaction to a database (say, SQL Server)?

When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of "some_field" in django admin panel. You can also use:

def __str__(self):
    return self.some_field

Does PHP have threading?

Here is an example of what Wilco suggested:

$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);

Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:

exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
     // less than 2 rows in the ps, therefore report is complete
}

There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

Why does viewWillAppear not get called when an app comes back from the background?

Swift

Short answer

Use a NotificationCenter observer rather than viewWillAppear.

override func viewDidLoad() {
    super.viewDidLoad()

    // set observer for UIApplication.willEnterForegroundNotification
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
    // do stuff
}

Long answer

To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

import UIKit
class ViewController: UIViewController {

    // MARK: - Overrides

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        // add notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        print("view will appear")
    }

    override func viewDidAppear(_ animated: Bool) {
        print("view did appear")
    }

    // MARK: - Notification oberserver methods

    @objc func didBecomeActive() {
        print("did become active")
    }

    @objc func willEnterForeground() {
        print("will enter foreground")
    }

}

On first starting the app, the output order is:

view did load
view will appear
did become active
view did appear

After pushing the home button and then bringing the app back to the foreground, the output order is:

will enter foreground
did become active 

So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

Note

As of iOS 9 and later, you don't need to remove the observer. The documentation states:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

Using cURL with a username and password?

If you are on a system that has Gnome keyring app a solution that avoids exposing the password directly is to use gkeyring.py to extract the password from the keyring:

server=server.example.com
file=path/to/my/file
user=my_user_name
pass=$(gkeyring.py -k login -tnetwork -p user=$user,server=$server -1)

curl -u $user:$pass ftps://$server/$file -O

How to export data from Excel spreadsheet to Sql Server 2008 table

In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:

On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.

After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Eclipse error: "The import XXX cannot be resolved"

I resolved this issue by updating the project: right click on the Maven project, select Maven -> Update Project -> select checkbox Force Updates of Snapshots/Releases.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

You need to close your port if you are a linux user then type

fuser -k 8080/tcp

Spring Boot @Value Properties

I´d like to mention, that I used spring boot version 1.4.0 and since this version you can only write:

@Component
public class MongoConnection {

@Value("${spring.data.mongodb.host}")
private String mongoHost;

@Value("${spring.data.mongodb.port}")
private int mongoPort;

@Value("${spring.data.mongodb.database}")
private String mongoDB;
}

Then inject class whenever you want.

EDIT:

From nowadays I would use @ConfigurationProperties because you are able to inject property values in your POJOs. Keep hierarchical sort above your properties. Moreover, you can put validations above POJOs attributes and so on. Take a look at the link

How to access the php.ini from my CPanel?

You cant do it on shared hosting , Add ticket to support of hosting for same ( otherwise you can look for dedicated server where you can manage anything )

NLTK and Stopwords Fail #lookuperror

If you want to manually install NLTK Corpus.

1) Go to http://www.nltk.org/nltk_data/ and download your desired NLTK Corpus file.

2) Now in a Python shell check the value of nltk.data.path

3) Choose one of the path that exists on your machine, and unzip the data files into the corpora sub directory inside.

4) Now you can import the data from nltk.corpos import stopwords

Reference: https://medium.com/@satorulogic/how-to-manually-download-a-nltk-corpus-f01569861da9

How do I get the current year using SQL on Oracle?

Use extract(datetime) function it's so easy, simple.

It returns year, month, day, minute, second

Example:

select extract(year from sysdate) from dual;

CSS @media print issues with background-color;

Got it:

CSS:

box-shadow: inset 0 0 0 1000px gold;

Works for all boxes - including table cells !!!

  • (If the PDF-printer output file is to be believed..?)
  • Only tested in Chrome + Firefox on Ubuntu...

Reduce left and right margins in matplotlib plot

plt.savefig("circle.png", bbox_inches='tight',pad_inches=-1)

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

HTML code for INR

?? Indian rupee sign. HTML: &#8377; — ₹ or &#x20B9; — also ₹, corresponding to Unicode U+20B9.

How to watch for form changes in Angular

If you are using FormBuilder, see @dfsq's answer.

If you are not using FormBuilder, there are two ways to be notified of changes.

Method 1

As discussed in the comments on the question, use an event binding on each input element. Add to your template:

<input type="text" class="form-control" required [ngModel]="model.first_name"
         (ngModelChange)="doSomething($event)">

Then in your component:

doSomething(newValue) {
  model.first_name = newValue;
  console.log(newValue)
}

The Forms page has some additional information about ngModel that is relevant here:

The ngModelChange is not an <input> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.

The other oddity is the template expression, model.name = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires..

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.

In your case, I suppose you want to do something special.

Method 2

Define a local template variable and set it to ngForm.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  ....
  <input type="text" ngControl="firstName" class="form-control" 
   required [(ngModel)]="model.first_name">
  ...
  <input type="text" ngControl="lastName" class="form-control" 
   required [(ngModel)]="model.last_name">

class MyForm {
  @ViewChild('myForm') form;
  ...
  ngAfterViewInit() {
    console.log(this.form)
    this.form.control.valueChanges
      .subscribe(values => this.doSomething(values));
  }
  doSomething(values) {
    console.log(values);
  }
}

plunker

For more information on Method 2, see Savkin's video.

See also @Thierry's answer for more information on what you can do with the valueChanges observable (such as debouncing/waiting a bit before processing changes).

Change the On/Off text of a toggle button Android

You can use the following to set the text from the code:

toggleButton.setText(textOff);
// Sets the text for when the button is first created.

toggleButton.setTextOff(textOff);
// Sets the text for when the button is not in the checked state.

toggleButton.setTextOn(textOn);
// Sets the text for when the button is in the checked state.

To set the text using xml, use the following:

android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked." 

This information is from here

TypeError: 'module' object is not callable

I know this thread is a year old, but the real problem is in your working directory.

I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :)

Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Points to remember when extending SQLiteOpenHelper

  1. super(context, DBName, null, DBversion); - This should be invoked first line of constructor
  2. override onCreate and onUpgrade (if needed)
  3. onCreate will be invoked only when getWritableDatabase() or getReadableDatabase() is executed. And this will only invoked once when a DBName specified in the first step is not available. You can add create table query on onCreate method
  4. Whenever you want to add new table just change DBversion and do the queries in onUpgrade table or simply uninstall then install the app.

Retrieve version from maven pom.xml in code

Use this Library for the ease of a simple solution. Add to the manifest whatever you need and then query by string.

 System.out.println("JAR was created by " + Manifests.read("Created-By"));

http://manifests.jcabi.com/index.html

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

HTML colspan in CSS

You could trying using a grid system like http://960.gs/

Your code would be something like this, assuming you're using a "12 column" layout:

<div class="container_12">
<div class="grid_4">1</div><div class="grid_4">2</div><div class="grid_4">3</div>
<div class="clear"></div>
<div class="grid_12">123</div>
</div>