Programs & Examples On #Inversion

ngrok command not found

The only solution that worked for me was

yarn global add ngrok 
yarn global add exp

with npm I was getting permission errors etc..

What are the differences between ArrayList and Vector?

As the documentation says, a Vector and an ArrayList are almost equivalent. The difference is that access to a Vector is synchronized, whereas access to an ArrayList is not. What this means is that only one thread can call methods on a Vector at a time, and there's a slight overhead in acquiring the lock; if you use an ArrayList, this isn't the case. Generally, you'll want to use an ArrayList; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an ArrayList, you can use the Collections.synchronizedList function to create a synchronized list, thus getting you the equivalent of a Vector.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

Yes, it does. From the AdMob page:

The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.

DateTime fields from SQL Server display incorrectly in Excel

This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,

SELECT CONVERT (varchar, getdate(), 120) AS Date

If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.

AttributeError: 'module' object has no attribute

Circular imports cause problems, but Python has ways to mitigate it built-in.

The problem is when you run python a.py, it runs a.py but not mark it imported as a module. So in turn a.py -> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi(), it can't find anything.

Note that the b.hi() that got executed is during a.py -> module b -> module a, not in a.py directly.

In your specific example, you can just run python -c 'import a' at top-level, so the first execution of a.py is registered as importing a module.

How to return a part of an array in Ruby?

Ruby 2.6 Beginless/Endless Ranges

(..1)
# or
(...1)

(1..)
# or
(1...)

[1,2,3,4,5,6][..3]
=> [1, 2, 3, 4]

[1,2,3,4,5,6][...3]
 => [1, 2, 3]

ROLES = %w[superadmin manager admin contact user]
ROLES[ROLES.index('admin')..]
=> ["admin", "contact", "user"]

Generic deep diff between two objects

Here is a typescript version of @sbgoran code

export class deepDiffMapper {

  static VALUE_CREATED = 'created';
  static VALUE_UPDATED = 'updated';
  static VALUE_DELETED = 'deleted';
  static VALUE_UNCHANGED ='unchanged';

  protected isFunction(obj: object) {
    return {}.toString.apply(obj) === '[object Function]';
  };

  protected isArray(obj: object) {
      return {}.toString.apply(obj) === '[object Array]';
  };

  protected isObject(obj: object) {
      return {}.toString.apply(obj) === '[object Object]';
  };

  protected isDate(obj: object) {
      return {}.toString.apply(obj) === '[object Date]';
  };

  protected isValue(obj: object) {
      return !this.isObject(obj) && !this.isArray(obj);
  };

  protected compareValues (value1: any, value2: any) {
    if (value1 === value2) {
        return deepDiffMapper.VALUE_UNCHANGED;
    }
    if (this.isDate(value1) && this.isDate(value2) && value1.getTime() === value2.getTime()) {
        return deepDiffMapper.VALUE_UNCHANGED;
    }
    if ('undefined' == typeof(value1)) {
        return deepDiffMapper.VALUE_CREATED;
    }
    if ('undefined' == typeof(value2)) {
        return deepDiffMapper.VALUE_DELETED;
    }

    return deepDiffMapper.VALUE_UPDATED;
  }

  public map(obj1: object, obj2: object) {
      if (this.isFunction(obj1) || this.isFunction(obj2)) {
          throw 'Invalid argument. Function given, object expected.';
      }
      if (this.isValue(obj1) || this.isValue(obj2)) {
          return {
              type: this.compareValues(obj1, obj2),
              data: (obj1 === undefined) ? obj2 : obj1
          };
      }

      var diff = {};
      for (var key in obj1) {
          if (this.isFunction(obj1[key])) {
              continue;
          }

          var value2 = undefined;
          if ('undefined' != typeof(obj2[key])) {
              value2 = obj2[key];
          }

          diff[key] = this.map(obj1[key], value2);
      }
      for (var key in obj2) {
          if (this.isFunction(obj2[key]) || ('undefined' != typeof(diff[key]))) {
              continue;
          }

          diff[key] = this.map(undefined, obj2[key]);
      }

      return diff;

  }
}

Checking session if empty or not

if (HttpContext.Current.Session["emp_num"] != null)
{
     // code if session is not null
}
  • if at all above fails.

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

Is there StartsWith or Contains in t sql with variables?

It seems like what you want is http://msdn.microsoft.com/en-us/library/ms186323.aspx.

In your example it would be (starts with):

set @isExpress = (CharIndex('Express Edition', @edition) = 1)

Or contains

set @isExpress = (CharIndex('Express Edition', @edition) >= 1)

'git status' shows changed files, but 'git diff' doesn't

There are a few reasons why git status might show a difference but git diff might not.

  • The mode (permission bits) of the file changed-- for example, from 777 to 700.

  • The line feed style changed from CRLF (DOS) to LF (UNIX)

The easiest way to find out what happened is to run git format-patch HEAD^ and see what the generated patch says.

How to change colors of a Drawable in Android?

Too late but in case someone need it:

   fun setDrawableColor(drawable: Drawable, color: Int) :Drawable {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
            return drawable
        } else {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            return drawable
        }
    }

Extract a substring using PowerShell

PS> $a = "-----start-------Hello World------end-------"
PS> $a.substring(17, 11)
         or
PS> $a.Substring($a.IndexOf('H'), 11)

$a.Substring(argument1, argument2) --> Here argument1 = Starting position of the desired alphabet and argument2 = Length of the substring you want as output.

Here 17 is the index of the alphabet 'H' and since we want to Print till Hello World, we provide 11 as the second argument

Reverse order of foreach list items

Or you could use the array_reverse function.

How do I check if a C++ string is an int?

Here is another solution.

try
{
  (void) std::stoi(myString); //cast to void to ignore the return value   
  //Success! myString contained an integer
} 
catch (const std::logic_error &e)
{   
  //Failure! myString did not contain an integer
}

Trying to check if username already exists in MySQL database using PHP

TRY THIS ONE

 mysql_connect('localhost','dbuser','dbpass');

$query = "SELECT username FROM Users WHERE username='".$username."'";
mysql_select_db('dbname');

    $result=mysql_query($query);

   if (mysql_num_rows($query) != 0)
   {
     echo "Username already exists";
    }

    else
   {
     ...
    }

POI setting Cell Background to a Custom Color

As pointed in Vlad's answer, you are running out of free color slots. One way to get around that would be to cache the colors: whenever you try a RGB combination, the routine should first check if the combination is in the cache; if it is in the cache, then it should use that one instead of creating a new one from scratch; new colors would then only be created if they're not yet in cache.

Here's the implementation I use; it uses XSSF plus Guava's LoadingCache and is geared towards generationg XSSF colors from CSS rgb(r, g, b) declarations, but it should be relatively trivial to adapt it to HSSF:

    private final LoadingCache<String, XSSFColor> colorsFromCSS = CacheBuilder.newBuilder()
            .build(new CacheLoader<String, XSSFColor>() {

                private final Pattern RGB = Pattern.compile("rgb\\(\\s*(\\d+)\\s*, \\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");

                @Override
                public XSSFColor load(String style) throws Exception {
                    Matcher mat = RGB.matcher(style);
                    if (!mat.find()) {
                        throw new IllegalStateException("Couldn't read CSS color: " + style);
                    }                       
                    return new XSSFColor(new java.awt.Color(
                            Integer.parseInt(mat.group(1)), 
                            Integer.parseInt(mat.group(2)), 
                            Integer.parseInt(mat.group(3))));
                }

            });

Perhaps someone else could post a HSSF equivalent? ;)

Making TextView scrollable on Android

When you are done with scrollable, add this line to the view's last line when you enter anything in the view:

((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

Get type of a generic parameter in Java with reflection

This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

JAVA_HOME should point to a JDK not a JRE

I added JAVA_HOME path in user variable and omit the "/bin". I tried every method given here but only this worked for me.

Business logic in MVC

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Waqas Raja's answer with some LINQ lambda fun:

List<int> listValues = new List<int>();
Request.Form.AllKeys
    .Where(n => n.StartsWith("List"))
    .ToList()
    .ForEach(x => listValues.Add(int.Parse(Request.Form[x])));

UITableView - change section header color

 -(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
  forSection:(NSInteger)section
  {
        if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
        {
             UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
             UIView *content = castView.contentView;
             UIColor *color = [UIColor whiteColor]; // substitute your color here
             content.backgroundColor = color;
             [castView.textLabel setTextColor:[UIColor blackColor]];
        }
 }

Find index of last occurrence of a substring in a string

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

How to create a GUID / UUID

UUID with timestamp built in (emitter/parser)
I will also post my simple approach to generating a valid UUID v4 with very strong uniqueness and fast runtime. The basic idea is not new, but approach is different. I use a timestamp in milliseconds from the date.now() (in Node.js library, which I'll point later, I use nanoseconds timestamp from process.hrtime.bigint()), and then add a random 5 digit number (10000-90000) to the end of the timestamp string. After merging the strings, I just form a valid UUID from digits and a pair of special characters, so that my UUID consists only of digits and a few non-numeric characters. Please check it out below:

_x000D_
_x000D_
/*
 * uuid-timestamp (emitter)
 * UUID v4 based on timestamp
 *
 * Created by tarkh
 * tarkh.com (C) 2020
 */
const uuidEmit = () => {
  // Get now time
  const n = Date.now();
  // Generate random
  const r = Math.random();
  // Stringify now time and generate additional random number
  const s = String(n) + String(~~(r*9e4)+1e4);
  // Form UUID and return it
  return `${s.slice(0,8)}-${s.slice(8,12)}-4${s.slice(12,15)}-${[8,9,'a','b'][~~(r*3)]}${s.slice(15,18)}-${s.slice(s.length-12)}`;
};

// Generate 5 UUIDs
console.log(`${uuidEmit()}
${uuidEmit()}
${uuidEmit()}
${uuidEmit()}
${uuidEmit()}`);
_x000D_
_x000D_
_x000D_

Looking at the results, you obviously see that the first part of UUIDs is the same, and then comes randomness. This is because I inserted the timestamp into the UUID linearly. The code will produce a new UUID every millisecond (nanosecond in Node.js library) + add a random 5-digit number to the end, so we end up with very approximate collision probability around 1 in 10 million per second. If we use Node.js library, our very approximate collision probability goes to 1 in 10 billion per second.

Timestamp built into the UUID
Since we insert a timestamp into the UUID linearly, we get a feature (good or bad - depends on the task) - ability to easily extract this timestamp back from the UUID. This way we can understand when UUID was released:

_x000D_
_x000D_
/*
 * uuid-timestamp (parser)
 * UUID v4 based on timestamp
 *
 * Created by tarkh
 * tarkh.com (C) 2020
 */
const uuidParse = (uuid) => {
  // Get current timestamp string length
  let tl = String(Date.now()).length;
  // Strip out timestamp from UUID
  let ts = '';
  let i = -1;
  while(tl--) {
    i++;
    if(i===8||i===13||i===14||i===18||i===19||i===23) {
      tl++;
      continue;
    }
    ts += uuid[i];
  }
  return Number(ts);
};

// Get the timestamp when UUID was emitted
const time = uuidParse('15970688-7109-4530-8114-887109530114');

// Covert timestamp to date and print it
console.log(new Date(time).toUTCString());
_x000D_
_x000D_
_x000D_

Node.js
NPM version of my code above available as Node.js module. This version is even more powerful in generating unique values, because instead of millisecond timestamp it uses nanoseconds from combination of system time and process.hrtime.bigint() diff.

Benchmarks
At the end of my post, I want to do some performance tests based on some of the answers from this topic. Of course, my decision is not the fastest, but it certainly takes the top positions.
Check jsBench here

Twitter Bootstrap - borders

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

.row {
    zoom: 1;
    margin-left: -20px;
}

.row > [class*="span"] {
    display: inline;
    float: left;
    margin-left: 20px;
}

.span4 {
    width: 220px;
}

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

Screenshot of Example Page

For example, to allow for the left border on the sidebar, they added this CSS in the <head> after the the main <link href="../bootstrap.css" rel="stylesheet">.

.content .span4 {
    margin-left: 0;
    padding-left: 19px;
    border-left: 1px solid #eee;
}

You'll see they've reduced padding-left by 1px to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

gnuplot : plotting data from multiple input files in a single graph

You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

e.g.

filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines

and

filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines

How to rename a table column in Oracle 10g

alter table table_name 
rename column old_column_name/field_name to new_column_name/field_name;

example: alter table student column name to username;

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

read -r -p "Are you sure? [Y/n]" response
  response=${response,,} # tolower
  if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
      your-action-here
  fi

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

CSS height 100% percent not working

For code mirror divs refer to the manual, these sections might be useful to you:

http://codemirror.net/demo/fullscreen.html

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  theme: "night",
  extraKeys: {
    "F11": function(cm) {
      cm.setOption("fullScreen", !cm.getOption("fullScreen"));
    },
    "Esc": function(cm) {
      if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
    }
  }
});

And also take a look at:

http://codemirror.net/demo/resize.html

Also a comment:

Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.

Java JDBC - How to connect to Oracle using Service Name instead of SID

This should be working: jdbc:oracle:thin//hostname:Port/ServiceName=SERVICE_NAME

Why does PEP-8 specify a maximum line length of 79 characters?

because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).

How to verify a Text present in the loaded page through WebDriver

Below code is most suitable way to verify a text on page. You can use any one out of 8 locators as per your convenience.

String Verifytext= driver.findElement(By.tagName("body")).getText().trim(); Assert.assertEquals(Verifytext, "Paste the text here which needs to be verified");

How to pass data between fragments

If you use Roboguice you can use the EventManager in Roboguice to pass data around without using the Activity as an interface. This is quite clean IMO.

If you're not using Roboguice you can use Otto too as a event bus: http://square.github.com/otto/

Update 20150909: You can also use Green Robot Event Bus or even RxJava now too. Depends on your use case.

How do I find all of the symlinks in a directory tree?

This is the best thing I've found so far - shows you the symlinks in the current directory, recursively, but without following them, displayed with full paths and other information:

find ./ -type l -print0 | xargs -0 ls -plah

outputs looks about like this:

lrwxrwxrwx 1 apache develop 99 Dec  5 12:49 ./dir/dir2/symlink1 -> /dir3/symlinkTarget
lrwxrwxrwx 1 apache develop 81 Jan 10 14:02 ./dir1/dir2/dir4/symlink2 -> /dir5/whatever/symlink2Target
etc...

Java - How to convert type collection into ArrayList?

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

Add User to Role ASP.NET Identity

Check this link: Assigning Roles to Users. You can add a step to your CreateUserWIzard control and choose the roles in that step.

<asp:CreateUserWizard ID="RegisterUserWithRoles" runat="server" 
    ContinueDestinationPageUrl="~/Default.aspx" LoginCreatedUser="False" 
    onactivestepchanged="RegisterUserWithRoles_ActiveStepChanged">
    <WizardSteps>
        <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
        </asp:CreateUserWizardStep>
        <asp:WizardStep ID="SpecifyRolesStep" runat="server" AllowReturn="False" 
            StepType="Step" Title="Specify Roles">
            <h3>Choose the role.</h3>
            <asp:CheckBoxList ID="RoleList" runat="server">
            </asp:CheckBoxList>
        </asp:WizardStep>
        <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
        </asp:CompleteWizardStep>
    </WizardSteps>
</asp:CreateUserWizard>

And in the code-behind you will have:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // Reference the SpecifyRolesStep WizardStep 
        WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;

        // Reference the RoleList CheckBoxList 
        CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;

        // Bind the set of roles to RoleList 
        RoleList.DataSource = Roles.GetAllRoles();
        RoleList.DataBind();
    } 
}
protected void RegisterUserWithRoles_ActiveStepChanged(object sender, EventArgs e)
{
    // Have we JUST reached the Complete step? 
    if (RegisterUserWithRoles.ActiveStep.Title == "Complete")
    {
        // Reference the SpecifyRolesStep WizardStep 
        WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;

        // Reference the RoleList CheckBoxList 
        CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;

        // Add the checked roles to the just-added user 
        foreach (ListItem li in RoleList.Items)
        {
            if (li.Selected)
                Roles.AddUserToRole(RegisterUserWithRoles.UserName, li.Text);
        }
    }
}

Insert and set value with max()+1 problems

Use table alias in subquery:

INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES 
  ((SELECT MAX( customer_id ) FROM customers C) +1, 'jim', 'sock')

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

How to run html file on localhost?

As Nora suggests, you can use the python simple server. Navigate to the folder from which you want to serve your html page, then execute python -m SimpleHTTPServer. Now you can use your web-browser and navigate to http://localhost:8000/ where your page is being served. If your page is named index.html then the server automatically loads that for you. If you want to access any other page, you'll need to browse to http://localhost:8000/{your page name}

Execute jar file with multiple classpath libraries from command prompt

This will not work java -cp lib\*.jar -jar myproject.jar. You have to put it jar by jar.

So in case of commons-codec-1.3.jar.

java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar and so on.

The other solution might be putting all your jars to ext directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

Facebook OAuth "The domain of this URL isn't included in the app's domain"

I had the same problem,

I just added the link of my local adress http://localhost/Facebook%20Login%20Test.html to Site URL in my application setting https://developers.facebook.com/apps.

Now it works fine :) I hope this was useful ;)

Set folder browser dialog start location

Set the SelectedPath property before you call ShowDialog ...

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

Will start them at C:\Temp

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type attribute as required while HTML5 has it as optional, defaulting to text/javascript. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script> is valid and a good choice.

As to what should go in the type attribute, the MIME type application/javascript registered in 2006 is intended to replace text/javascript and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:

This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

However, IE up to and including version 8 doesn't execute script inside a <script> element with a type attribute of either application/javascript or application/ecmascript, so if you need to support old IE, you're stuck with text/javascript.

How to install pip for Python 3 on Mac OS X?

Also, it's worth to mention that Max OSX/macOS users can just use Homebrew to install pip3.

$> brew update
$> brew install python3
$> pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

How do I run Java .class files?

You have to put java in lower case and you have to add .class!

java HelloWorld2.class

Manually install Gradle and use it in Android Studio

Step 1: Go to the download site from Gradle: https://gradle.org/releases/

Step 2: Extract the downloaded zip file into a directory.

Step 2: Hit Ctrl + Alt + S (mac: ? + ,) in Android studio/Intellij IDEA

Step 3: Goto: Build, Execution, Deployment >> Build Tools >> Gradle (Or just type in the searchbar Gradle)

Step 4: Select: (X) Use local gradle distribution and set Gradle home to your extracted Gradle directory. Click on apply.

Step 5: Get rid of your unnecessary gradle files delete:
- MyApp/gradle/
- gradlew
- gradlew.bat

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

Replace Line Breaks in a String C#

If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.

line = line.Replace(Environment.NewLine, "newLineReplacement");

However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

there are two way:

First :

Inside your CD of SQL Server 2012

you can go to this path \redist\VisualStudioShell.

And you most install this file VS10sp1-KB983509.msp.

After several minutes your problem fix.

Restart your computer and then fire SetUp of SQL Server 2012.

See this picture.

enter image description here

Secound :

But if you want download online Service Pack 1 view This Link

And press download.

After download run this exe file and let it download and fix your VS2010 to VS2010 SP1.

And then restart your windows.

After this operation you can install SQL Server 2012

enter image description here

How to use parameters with HttpPost

You can also use this approach in case you want to pass some http parameters and send a json request:

(note: I have added in some extra code just incase it helps any other future readers)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("http://google.ug");
    uriBuilder.addParameters(postParameters);

    HttpPost postRequest = new HttpPost(uriBuilder.build());
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
    postRequest.setEntity(entity);

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(20);

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(HttpClientPool.connTimeout)
            .setConnectTimeout(HttpClientPool.connTimeout)
            .setConnectionRequestTimeout(HttpClientPool.readTimeout)
            .build();

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;
    }

    //release all resources held by the responseHttpEntity
    EntityUtils.consume(responseHttpEntity);

    //close the stream
    response.close();

    // Close the connection manager.
    connManager.close();
}

What is the quickest way to HTTP GET in Python?

Without further necessary imports this solution works (for me) - also with https:

try:
    import urllib2 as urlreq # Python 2.x
except:
    import urllib.request as urlreq # Python 3.x
req = urlreq.Request("http://example.com/foo/bar")
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')
urlreq.urlopen(req).read()

I often have difficulty grabbing the content when not specifying a "User-Agent" in the header information. Then usually the requests are cancelled with something like: urllib2.HTTPError: HTTP Error 403: Forbidden or urllib.error.HTTPError: HTTP Error 403: Forbidden.

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The number of binary trees can be calculated using the catalan number.

The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of Left binary search sub-trees) * (Number of Right binary search sub-trees) * (Ways to choose the root)

In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are 1, 2, 3, 4, ...., n. Also, let the number of BST be represented by f(n) for n elements.

Now we have the multiple cases for choosing the root.

  1. choose 1 as root, no element can be inserted on the left sub-tree. n-1 elements will be inserted on the right sub-tree.
  2. Choose 2 as root, 1 element can be inserted on the left sub-tree. n-2 elements can be inserted on the right sub-tree.
  3. Choose 3 as root, 2 element can be inserted on the left sub-tree. n-3 elements can be inserted on the right sub-tree.

...... Similarly, for i-th element as the root, i-1 elements can be on the left and n-i on the right.

These sub-trees are itself BST, thus, we can summarize the formula as:

f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)

Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.

Final Formula

How to delete a workspace in Eclipse?

Just go to the \eclipse-java-helios-SR2-win32\eclipse\configuration.settings directory and change or remove org.eclipse.ui.ide.prefs file.

Serializing and submitting a form with jQuery and PHP

Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:

 <textarea name="comentarii" cols="36" rows="5" placeholder="Message>  

Is there a way to pass javascript variables in url?

Summary

With either string concatenation or string interpolation (via template literals).

Here with JavaScript template literal:

function geoPreview() {
    var lat = document.getElementById("lat").value;
    var long = document.getElementById("long").value;

    window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}

Both parameters are unused and can be removed.

Remarks

String Concatenation

Join strings with the + operator:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";

String Interpolation

For more concise code, use JavaScript template literals to replace expressions with their string representations. Template literals are enclosed by `` and placeholders surrounded with ${}:

window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;

Template literals are available since ECMAScript 2015 (ES6).

How to write a test which expects an Error to be thrown in Jasmine?

Try using an anonymous function instead:

expect( function(){ parser.parse(raw); } ).toThrow(new Error("Parsing is not possible"));

you should be passing a function into the expect(...) call. Your incorrect code:

// incorrect:
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));

is trying to actually call parser.parse(raw) in an attempt to pass the result into expect(...),

How can I use the apply() function for a single column?

Given the following dataframe df and the function complex_function,

  import pandas as pd

  def complex_function(x, y=0):
      if x > 5 and x > y:
          return 1
      else:
          return 2

  df = pd.DataFrame(data={'col1': [1, 4, 6, 2, 7], 'col2': [6, 7, 1, 2, 8]})
     col1  col2
  0     1     6
  1     4     7
  2     6     1
  3     2     2
  4     7     8

there are several solutions to use apply() on only one column. In the following I will explain them in detail.

I. Simple solution

The straightforward solution is the one from @Fabio Lamanna:

  df['col1'] = df['col1'].apply(complex_function)

Output:

     col1  col2
  0     2     6
  1     2     7
  2     1     1
  3     2     2
  4     1     8

Only the first column is modified, the second column is unchanged. The solution is beautiful. It is just one line of code and it reads almost like english: "Take 'col1' and apply the function complex_function to it."

However, if you need data from another column, e.g. 'col2', it's not working. If you want to pass the values of 'col2' to variable y of the complex_function, you need something else.

II. Solution using the whole dataframe

Alternatively, you could use the whole dataframe as described in this or this SO post:

  df['col1'] = df.apply(lambda x: complex_function(x['col1']), axis=1)

or if you prefer (like me) a solution without a lambda function:

  def apply_complex_function(x): return complex_function(x['col1'])
  df['col1'] = df.apply(apply_complex_function, axis=1) 

There is a lot going on in this solution that needs to be explained. The apply() function works on pd.Series and pd.DataFrame. But you cannot use df['col1'] = df.apply(complex_function).loc[:, 'col1'], because it would throw a ValueError.

Hence, you need to give the information which column to use. To complicate things, the apply() function does only accept callables. To solve this, you need to define a (lambda) function with the column x['col1'] as argument; i.e. we wrap the column information in another function.

Unfortunately, the default value of the axis parameter is zero (axis=0), which means it will try executing column-wise and not row-wise. This wasn't a problem in the first solution, because we gave apply() a pd.Series. But now the input is a dataframe and we must be explicit (axis=1). (I marvel how often I forget this.)

Whether you prefer the version with the lambda function or without is subjective. In my opinion the line of code is complicated enough to read even without a lambda function thrown in. You only need the (lambda) function as a wrapper. It is just boiler code. A reader should not be bothered with it.

Now, you can modify this solution easily to take the second column into account:

    def apply_complex_function(x): return complex_function(x['col1'], x['col2'])
    df['col1'] = df.apply(apply_complex_function, axis=1)

Output:

     col1  col2
  0     2     6
  1     2     7
  2     1     1
  3     2     2
  4     2     8

At index 4 the value has changed from 1 to 2, because the first condition 7 > 5 is true but the second condition 7 > 8 is false.

Note that you only needed to change the first line of code (i.e. the function) and not the second line.


Side note

Never put the column information into your function.

  def bad_idea(x):
      return x['col1'] ** 2

By doing this, you make a general function dependent on a column name! This is a bad idea, because the next time you want to use this function, you cannot. Worse: Maybe you rename a column in a different dataframe just to make it work with your existing function. (Been there, done that. It is a slippery slope!)


III. Alternative solutions without using apply()

Although the OP specifically asked for a solution with apply(), alternative solutions were suggested. For example, the answer of @George Petrov suggested to use map(), the answer of @Thibaut Dubernet proposed assign().

I fully agree that apply() is seldom the best solution, because apply() is not vectorized. It is an element-wise operation with expensive function calling and overhead from pd.Series.

One reason to use apply() is that you want to use an existing function and performance is not an issue. Or your function is so complex that no vectorized version exists.

Another reason to use apply() is in combination with groupby(). Please note that DataFrame.apply() and GroupBy.apply() are different functions.

So it does make sense to consider some alternatives:

  • map() only works on pd.Series, but accepts dict and pd.Series as input. Using map() with a function is almost interchangeable with using apply(). It can be faster than apply(). See this SO post for more details.
  df['col1'] = df['col1'].map(complex_function)
  • applymap() is almost identical for dataframes. It does not support pd.Series and it will always return a dataframe. However, it can be faster. The documentation states: "In the current implementation applymap calls func twice on the first column/row to decide whether it can take a fast or slow code path.". But if performance really counts you should seek an alternative route.
  df['col1'] = df.applymap(complex_function).loc[:, 'col1']
  • assign() is not a feasible replacement for apply(). It has a similar behaviour in only the most basic use cases. It does not work with the complex_function. You still need apply() as you can see in the example below. The main use case for assign() is method chaining, because it gives back the dataframe without changing the original dataframe.
  df['col1'] = df.assign(col1=df.col1.apply(complex_function))

Annex: How to speed up apply?

I only mention it here because it was suggested by other answers, e.g. @durjoy. The list is not exhaustive:

  1. Do not use apply(). This is no joke. For most numeric operations, a vectorized method exists in pandas. If/else blocks can often be refactored with a combination of boolean indexing and .loc. My example complex_function could be refactored in this way.
  2. Refactor to Cython. If you have a complex equation and the parameters of the equation are in your dataframe, this might be a good idea. Check out the official pandas user guide for more information.
  3. Use raw=True parameter. Theoretically, this should improve the performance of apply() if you are just applying a NumPy reduction function, because the overhead of pd.Series is removed. Of course, your function has to accept an ndarray. You have to refactor your function to NumPy. By doing this, you will have a huge performance boost.
  4. Use 3rd party packages. The first thing you should try is Numba. I do not know swifter mentioned by @durjoy; and probably many other packages are worth mentioning here.
  5. Try/Fail/Repeat. As mentioned above, map() and applymap() can be faster - depending on the use case. Just time the different versions and choose the fastest. This approach is the most tedious one with the least performance increase.

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Open directory dialog

I'm using Ookii dialogs for a while and it work nice for WPF.

Here's the direct page:

https://github.com/augustoproiete/ookii-dialogs-wpf

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

On OSX and VSCode 1.50.0 all I had to do was to close and restart VSCode and the problem went away.

Oracle's default date format is YYYY-MM-DD, WHY?

I'm not an Oracle user (well, lately anyhow), BUT...

In most databases (and in precise language), a date doesn't include a time. Having a date doesn't imply that you are denoting a specific second on that date. Generally if you want a time as well as a date, that's called a timestamp.

alert() not working in Chrome

window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win

window is an instance of DOMWindow, and by setting something to window.alert, the correct implementation is being "shadowed", i.e. when accessing alert it is first looking for it on the window object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert property to window it finds it straight away and does not need to go up the prototype chain. Using delete window.alert you can remove the window own property and again expose the prototype implementation of alert. This may help explain:

window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

How do I find the size of a struct?

#include <stdio.h>

typedef struct { char* c; char b; } a;

int main()
{
    printf("sizeof(a) == %d", sizeof(a));
}

I get "sizeof(a) == 8", on a 32-bit machine. The total size of the structure will depend on the packing: In my case, the default packing is 4, so 'c' takes 4 bytes, 'b' takes one byte, leaving 3 padding bytes to bring it to the next multiple of 4: 8. If you want to alter this packing, most compilers have a way to alter it, for example, on MSVC:

#pragma pack(1)
typedef struct { char* c; char b; } a;

gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers!

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I believe it's better to use

$('#form-id').find('input').val('');

instead of

$('#form-id').children('input').val('');

incase you have checkboxes in your form use this to rest it:

$('#form-id').find('input:checkbox').removeAttr('checked');

SQL Server: Cannot insert an explicit value into a timestamp column

If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.

This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.

Define the selected option with the old input in Laravel / Blade

Okay, my 2 cents, using the default value of Laravel's old() function.

<select name="type">
    @foreach($options as $key => $text)
        <option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
    @endforeach
</select>

Maven – Always download sources and javadocs

Simply modify file mvn (or mvn.cmd if in windows) and add whatever command line switches you need (as mentioned by other answers). If you don't want to modify the install files (which I'd recommend), create a mymvn (or mymvn.cmd) wrapper that invokes the regular mvn with the parameters.

Visual Studio Code Tab Key does not insert a tab

Try CTR + M it will work like before.

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

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

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

Note that Get-ADUser defaults to using

 -SearchScope Subtree

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

C - gettimeofday for computing time?

To subtract timevals:

gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;

Assign width to half available screen width declaratively

Using constraints layout

  1. Add a Guideline
  2. Set the percentage to 50%
  3. Constrain your view to the Guideline and the parent.

enter image description here

If you are having trouble changing it to a percentage, then see this answer.

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    
</android.support.constraint.ConstraintLayout>

Show a popup/message box from a Windows batch file

A better option

set my_message=Hello world&& start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"


Description:
lines= amount of lines,plus 1
cols= amount of characters in the message, plus 3 (However, minimum must be 15)

Auto-calculated cols version:

set my_message=Hello world&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"

Append values to a set in Python

The way I like to do this is to convert both the original set and the values I'd like to add into lists, add them, and then convert them back into a set, like this:

setMenu = {"Eggs", "Bacon"}
print(setMenu)
> {'Bacon', 'Eggs'}
setMenu = set(list(setMenu) + list({"Spam"}))
print(setMenu)
> {'Bacon', 'Spam', 'Eggs'}
setAdditions = {"Lobster", "Sausage"}
setMenu = set(list(setMenu) + list(setAdditions))
print(setMenu)
> {'Lobster', 'Spam', 'Eggs', 'Sausage', 'Bacon'}

This way I can also easily add multiple sets using the same logic, which gets me an TypeError: unhashable type: 'set' if I try doing it with the .update() method.

When to use 'npm start' and when to use 'ng serve'?

npm start will run whatever you have defined for the start command of the scripts object in your package.json file.

So if it looks like this:

"scripts": {
  "start": "ng serve"
}

Then npm start will run ng serve.

How do I use the built in password reset/change views with my own templates

You just need to wrap the existing functions and pass in the template you want. For example:

from django.contrib.auth.views import password_reset

def my_password_reset(request, template_name='path/to/my/template'):
    return password_reset(request, template_name)

To see this just have a look at the function declartion of the built in views:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

How to output to the console and file?

Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.

import traceback
import sys

# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
    def __init__(self, filename):
        self.file = open(filename, 'w')
        self.stdout = sys.stdout

    def __enter__(self):
        sys.stdout = self

    def __exit__(self, exc_type, exc_value, tb):
        sys.stdout = self.stdout
        if exc_type is not None:
            self.file.write(traceback.format_exc())
        self.file.close()

    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)

    def flush(self):
        self.file.flush()
        self.stdout.flush()

To use the context manager:

print("Print")
with Tee('test.txt'):
    print("Print+Write")
    raise Exception("Test")
print("Print")

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

Ansible: Store command's stdout in new variable?

In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:

tasks:
       - shell: echo $(cat /etc/issue | awk {'print $7'})
         register: echo_content

       - shell: echo "It works"
         when: echo_content.stdout == "12"
         register: out
       - debug: var=out.stdout_lines

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

How to write super-fast file-streaming code in C#?

The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:

http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/

How to add an object to an array

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code

vb.net get file names in directory?

Try this:

Dim text As String = ""
Dim files() As String = IO.Directory.GetFiles(sFolder)

For Each sFile As String In files
    text &= IO.File.ReadAllText(sFile)
Next

Trying to detect browser close event

You can try something like this.

<html>
<head>
    <title>test</title>
    <script>
        function openChecking(){
            // alert("open");
            var width = Number(screen.width-(screen.width*0.25));  
            var height = Number(screen.height-(screen.height*0.25));
            var leftscr = Number((screen.width/2)-(width/2)); // center the window
            var topscr = Number((screen.height/2)-(height/2));
            var url = "";
            var title = 'popup';
            var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
            var popup = window.open(url, title, properties);
            var crono = window.setInterval(function() {
                if (popup.closed !== false) { // !== opera compatibility reasons
                    window.clearInterval(crono);
                    checkClosed();
                }
            }, 250); //we check if the window is closed every 1/4 second
        }   
        function checkClosed(){
            alert("closed!!");
            // do something
        }
    </script>    
</head>
<body>
    <button onclick="openChecking()">Click Me</button>
</body>
</html>

When the user closes the window, the callback will be fired.

In Python, how do you convert seconds since epoch to a `datetime` object?

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

How to change the value of attribute in appSettings section with Web.config transformation

If you want to make transformation your app setting from web config file to web.Release.config,you have to do the following steps. Let your web.config app setting file is this-

<appSettings>
     <add key ="K1" value="Debendra Dash"/>
  </appSettings>

Now here is the web.Release.config for the transformation.

<appSettings>
    <add key="K1" value="value dynamicly from Realease"
       xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"   
         />
  </appSettings>

This will transform the value of K1 to the new value in realese Mode.

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}

how to add script inside a php code?

You mean JavaScript? Just output it like anything else in the page:

<script type="text/javascript">
  <?php echo "alert('message');"; ?>
</script>

If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:

<script type="text/javascript">
  alert('<?php echo $custom_message; ?>');
</script>

Or you could even do something like this:

<script type="text/javascript">
  var alertMsg = '<?php echo $custom_message; ?>';
  alert(alertMsg);
</script>

Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

HTML table headers always visible at top of window when viewing a large table

I've made a proof-of-concept solution using jQuery.

View sample here.

I've now got this code in a Mercurial bitbucket repository. The main file is tables.html.

I'm aware of one issue with this: if the table contains anchors, and if you open the URL with the specified anchor in a browser, when the page loads, the row with the anchor will probably be obscured by the floating header.

Update 2017-12-11: I see this doesn't work with current Firefox (57) and Chrome (63). Not sure when and why this stopped working, or how to fix it. But now, I think the accepted answer by Hendy Irawan is superior.

Order a List (C#) by many fields?

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In my case, even though Target Framework of Project was 4.7.1, I was still getting same Error, Solution was to change httpRuntime in web.config under system.web to 4.7.1!

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

MySQL select 10 random rows from 600K rows fast

I needed a query to return a large number of random rows from a rather large table. This is what I came up with. First get the maximum record id:

SELECT MAX(id) FROM table_name;

Then substitute that value into:

SELECT * FROM table_name WHERE id > FLOOR(RAND() * max) LIMIT n;

Where max is the maximum record id in the table and n is the number of rows you want in your result set. The assumption is that there are no gaps in the record id's although I doubt it would affect the result if there were (haven't tried it though). I also created this stored procedure to be more generic; pass in the table name and number of rows to be returned. I'm running MySQL 5.5.38 on Windows 2008, 32GB, dual 3GHz E5450, and on a table with 17,361,264 rows it's fairly consistent at ~.03 sec / ~11 sec to return 1,000,000 rows. (times are from MySQL Workbench 6.1; you could also use CEIL instead of FLOOR in the 2nd select statement depending on your preference)

DELIMITER $$

USE [schema name] $$

DROP PROCEDURE IF EXISTS `random_rows` $$

CREATE PROCEDURE `random_rows`(IN tab_name VARCHAR(64), IN num_rows INT)
BEGIN

SET @t = CONCAT('SET @max=(SELECT MAX(id) FROM ',tab_name,')');
PREPARE stmt FROM @t;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @t = CONCAT(
    'SELECT * FROM ',
    tab_name,
    ' WHERE id>FLOOR(RAND()*@max) LIMIT ',
    num_rows);

PREPARE stmt FROM @t;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$

then

CALL [schema name].random_rows([table name], n);

JSON forEach get Key and Value

Try something like this:

var prop;
for(prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;

    console.log(prop + " - "+ obj[prop]);
}

jquery - Check for file extension before uploading

If you don't want to use $(this).val(), you can try:

var file_onchange = function () {
  var input = this; // avoid using 'this' directly

  if (input.files && input.files[0]) {
    var type = input.files[0].type; // image/jpg, image/png, image/jpeg...

    // allow jpg, png, jpeg, bmp, gif, ico
    var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;

    if (type_reg.test(type)) {
      // file is ready to upload
    } else {
      alert('This file type is unsupported.');
    }
  }
};

$('#file').on('change', file_onchange);

Hope this helps!

Description for event id from source cannot be found

Restart your system!

A friend of mine had exactly the same problem. He tried all the described options but nothing seemed to work. After many studies, also of Microsoft's description, he concluded to restart the system. It worked!!

It seems that the operating system does not in all cases refresh the list of registered event sources. Only after a restart you can be sure the event sources are registered properly.

Passing parameters in Javascript onClick event

This will work from JS without coupling to HTML:

document.getElementById("click-button").onclick = onClickFunction;

function onClickFunction()
{
    return functionWithArguments('You clicked the button!');
}

function functionWithArguments(text) {
    document.getElementById("some-div").innerText = text;
}

Making heatmap from pandas DataFrame

If you want an interactive heatmap from a Pandas DataFrame and you are running a Jupyter notebook, you can try the interactive Widget Clustergrammer-Widget, see interactive notebook on NBViewer here, documentation here

enter image description here

And for larger datasets you can try the in-development Clustergrammer2 WebGL widget (example notebook here)

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

SQL Case Sensitive String Compare

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

Did the trick.

Convert object array to hash map, indexed by an attribute value of the Object

With lodash:

const items = [
    { key: 'foo', value: 'bar' },
    { key: 'hello', value: 'world' }
];

const map = _.fromPairs(items.map(item => [item.key, item.val]));

// OR: if you want to index the whole item by key:
// const map = _.fromPairs(items.map(item => [item.key, item]));

The lodash fromPairs function reminds me about zip function in Python

Link to lodash

Find records from one table which don't exist in another

SELECT Call.ID, Call.date, Call.phone_number 
FROM Call 
LEFT OUTER JOIN Phone_Book 
  ON (Call.phone_number=Phone_book.phone_number) 
  WHERE Phone_book.phone_number IS NULL

Should remove the subquery, allowing the query optimiser to work its magic.

Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).

Installing SciPy with pip

To install scipy on windows follow these instructions:-

Step-1 : Press this link http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy to download a scipy .whl file (e.g. scipy-0.17.0-cp34-none-win_amd64.whl).

Step-2: Go to the directory where that download file is there from the command prompt (cd folder-name ).

Step-3: Run this command:

pip install scipy-0.17.0-cp27-none-win_amd64.whl

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I had the same error, then I tried <asp:PostBackTrigger ControlID="xyz"/> instead of AsyncPostBackTrigger .This worked for me. It is because we don't want a partial postback.

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

Hibernate Query By Example and Projections

I do not really think so, what I can find is the word "this." causes the hibernate not to include any restrictions in its query, which means it got all the records lists. About the hibernate bug that was reported, I can see it's reported as fixed but I totally failed to download the Patch.

MVC - Set selected value of SelectList

I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.

You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method

public ActionResult History(long id)
        {
            var app = new AppLogic();
            var historyVM = new ActivityHistoryViewModel();

            historyVM.ProcessHistory = app.GetActivity(id);
            historyVM.Process = app.GetProcess(id);
            var processlist = app.GetProcessList();

            historyVM.ProcessList = from process in processlist
                                    select new SelectListItem
                                    {
                                        Text = process.ProcessName,
                                        Value = process.ID.ToString(),
                                        Selected = long.Equals(process.ID, id)                                    

                                    };

            var listitems = new List<SelectListItem>();

            return View(historyVM);
        }

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

How to convert seconds to HH:mm:ss in moment.js

Until 24 hrs. As Duration.format is deprecated, with [email protected]

const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');

Best way to define private methods for a class in Objective-C

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.

What is the C# version of VB.net's InputDialog?

Not only should you add Microsoft.VisualBasic to your reference list for the project, but also you should declare 'using Microsoft.VisualBasic;' so you just have to use 'Interaction.Inputbox("...")' instead of Microsoft.VisualBasic.Interaction.Inputbox

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Calling a function of a module by using its name (a string)

locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

How can I see normal print output created during pytest run?

You can also enable live-logging by setting the following in pytest.ini or tox.ini in your project root.

[pytest]
log_cli = True

Or specify it directly on cli

pytest -o log_cli=True

jQuery Validate Plugin - Trigger validation of single field

Use Validator.element():

Validates a single element, returns true if it is valid, false otherwise.

Here is the example shown in the API:

var validator = $( "#myform" ).validate();
validator.element( "#myselect" );

.valid() validates the entire form, as others have pointed out. The API says:

Checks whether the selected form is valid or whether all selected elements are valid.

Refresh Page C# ASP.NET

Response.Redirect(Request.Url.ToString());

Git Bash won't run my python files?

Here is the SOLUTION

If you get Response:

  1. bash: python: command not found OR
  2. bash: conda: command not found

To the following Commands: when you execute python or python -V conda or conda --version in your Git/Terminal window

Background: This is because you either

  1. Installed Python in a location on your C Drive (C:) which is not directly in your program files folder.
  2. Installed Python maybe on the D Drive (D:) and your computer by default searches for it on your C:
  3. You have been told to go to your environment variables (located if you do a search for environment variables on your machines start menu) and change the "Path" variable on your computer and this still does not fix the problem.

Solution:

  1. At the command prompt, paste this command export PATH="$PATH:/c/Python36". That will tell Windows where to find Python. (This assumes that you installed it in C:\Python36)

  2. If you installed python on your D drive, paste this command export PATH="$PATH:/d/Python36".

  3. Then at the command prompt, paste python or python -V and you will see the version of Python installed and now you should not get Python 3.6.5

  4. Assuming that it worked correctly you will want to set up git bash so that it always knows where to find python. To do that, enter the following command: echo 'export PATH="$PATH:/d/Python36"' > .bashrc

Permanent Solution

  1. Go to BASH RC Source File (located on C: / C Drive in “C:\Users\myname”)

  2. Make sure your BASH RC Source File is receiving direction from your Bash Profile Source File, you can do this by making sure that your BASH RC Source File contains this line of code: source ~/.bash_profile

  3. Go to BASH Profile Source File (located on C: / C Drive in “C:\Users\myname”)

  4. Enter line: export PATH="$PATH:/D/PROGRAMMING/Applications/PYTHON/Python365" (assuming this is the location where Python version 3.6.5 is installed)

  5. This should take care of the problem permanently. Now whenever you open your Git Bash Terminal Prompt and enter “python” or “python -V” it should return the python version

Add Header and Footer for PDF using iTextsharp

This link will help you out completely(the Shortest and Most Elegant way):

Header Footer with PageEvent

        PdfPTable tbheader = new PdfPTable(3);
        tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbheader.DefaultCell.Border = 0;
        tbheader.AddCell(new Paragraph());
        tbheader.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbheader.AddCell(_cell2);
        float[] widths = new float[] { 20f, 20f, 60f };
        tbheader.SetWidths(widths);
        tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);

        PdfPTable tbfooter = new PdfPTable(3);
        tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbfooter.DefaultCell.Border = 0;
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbfooter.AddCell(_cell2);
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
        _celly.HorizontalAlignment = Element.ALIGN_RIGHT;
        _celly.Border = 0;
        tbfooter.AddCell(_celly);
        float[] widths1 = new float[] { 20f, 20f, 60f };
        tbfooter.SetWidths(widths1);
        tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);

How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

How do I center text vertically and horizontally in Flutter?

Text element inside Center of SizedBox work much better way, below Sample code

Widget build(BuildContext context) {
    return RawMaterialButton(
      fillColor: Colors.green,
      splashColor: Colors.greenAccent,
      shape: new CircleBorder(),
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(
              width: 100.0,
              height: 100.0,
              child: Center(
                child: Text(
                widget.buttonText,
                maxLines: 1,
                style: TextStyle(color: Colors.white)
              ),
              )
          )]
        ),
    ),
  onPressed: widget.onPressed
);
}

Enjoy coding ?

Thymeleaf using path variables to th:href

I think you can try this:

<a th:href="${'/category/edit/' + {category.id}}">view</a>

Or if you have "idCategory" this:

<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>

What is the best IDE to develop Android apps in?

All of the full-featured Java IDE's are good and share all of the same concepts and main features. If you can find your way around one you can probably do the same for any other without much trouble.

EDIT: Google gave us a wonderful gift with the new and free AndroidStudio is very good. I highly recommend it over Eclipse.

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Scrolling to element using webdriver?

You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains class:

from selenium.webdriver.common.action_chains import ActionChains

element = driver.find_element_by_id("my-id")

actions = ActionChains(driver)
actions.move_to_element(element).perform()

Or, you can also "scroll into view" via scrollIntoView():

driver.execute_script("arguments[0].scrollIntoView();", element)

If you are interested in the differences:

Setting the User-Agent header for a WebClient request

As a supplement to the other answers, here is Microsoft's guidance for user agent strings for its browsers. The user agent strings differ by browser (Internet Explorer and Edge) and operating system (Windows 7, 8, 10 and Windows Phone).

For example, here is the user agent string for Internet Explorer 11 on Windows 10:

Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko 

and for Internet Explorer for Windows Phone 8.1 Update:

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

Templates are given for the user agent strings for the Edge browser for Desktop, Mobile and WebView. See this answer for some Edge user agent string examples.

Finally, another page on MSDN provides guidance for IE11 on older desktop operating systems.

IE11 on Windows 8.1:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

and IE11 on Windows 7:

Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

Finding the source code for built-in Python functions?

Quite an unknown resource is the Python Developer Guide.

In a (somewhat) recent GH issue, a new chapter was added for to address the question you're asking: CPython Source Code Layout. If something should change, that resource will also get updated.

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

How to add conditional attribute in Angular 2?

Refining Günter Zöchbauer answer:

This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.

--EDIT-- It looks like angular has changed some things, so null will now work as expected. I've update the example to use null rather than undefined.

An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.

For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).

<a [attr.href]="currentUrl !== link.url ? link.url : null">

This is cleaner than using two *ngIf's on a span and anchor tag, I think. It's also perfect for adding a disabled attribute to a button.

Javascript: How to loop through ALL DOM elements on a page?

from this link
javascript reference

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
function findhead1()
{
    var tag, tags;
    // or you can use var allElem=document.all; and loop on it
    tags = "The tags in the page are:"
    for(i = 0; i < document.all.length; i++)
    {
        tag = document.all(i).tagName;
        tags = tags + "\r" + tag;
    }
    document.write(tags);
}

//  -->
</script>
</head>
<body onload="findhead1()">
<h1>Heading One</h1>
</body>
</html>

UPDATE:EDIT

since my last answer i found better simpler solution

function search(tableEvent)
    {
        clearResults()

        document.getElementById('loading').style.display = 'block';

        var params = 'formAction=SearchStocks';

        var elemArray = document.mainForm.elements;
        for (var i = 0; i < elemArray.length;i++)
        {
            var element = elemArray[i];

            var elementName= element.name;
            if(elementName=='formAction')
                continue;
            params += '&' + elementName+'='+ encodeURIComponent(element.value);

        }

        params += '&tableEvent=' + tableEvent;


        createXmlHttpObject();

        sendRequestPost(http_request,'Controller',false,params);

        prepareUpdateTableContents();//function js to handle the response out of scope for this question

    }

How do I download/extract font from chrome developers tools?

I found the Chrome option to be OK but there are quite a few steps to go through to get to the font files. Once you're there, the downloading is super easy. I usually use the dev tools in Safari as there are fewer steps. Just go to the page you want, click on "Show page source" or "show page resources" in the Developer menu (both work for this) and the page resources are listed in folders on the left hand side. Click the font folder and the fonts are listed. Right click and save file. If you are downloading a lot of font files from one site it may be quicker to work your way through Chrome's pathway as the "open in tab" does download the fonts quicker. If you're taking one or two fonts from a lot of different sites, Safari will be quicker overall.

clearing a char array c

It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.

On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.

How to stretch in width a WPF user control to its window?

Does setting the HorizontalAlignment to Stretch, and the Width to Auto on the user control achieve the desired results?

Compute mean and standard deviation by group for multiple variables in a data.frame

Here's another take on the data.table answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply instead of sapply):

library(data.table)
set.seed(1)
dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
#   ID mean.Obs_1 mean.Obs_2 mean.Obs_3  sd.Obs_1  sd.Obs_2  sd.Obs_3
#1:  1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
#2:  2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
#3:  3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

HTML favicon won't show on google chrome

1) Clear your chache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser, lets say safari. How did you import the favicon?

2) How you should add it:

Normal favicon:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

PNG/GIF favicon:

<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />

3) Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver).

4) Try to rename it from favicon.{whatever} to {yourfaviconname}.{whatever} but I would suggest you to still have the normal favicon. This has solved my issue on IE.

5) Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:

<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />

Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

How do I get time of a Python program's execution?

You can use the Python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. This answer to another Stack Overflow question is pretty good. It's always good to have a look in the documentation too.

Here's an example how to profile a script using cProfile from a command line:

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

How to error handle 1004 Error with WorksheetFunction.VLookup?

From my limited experience, this happens for two main reasons:

  1. The lookup_value (arg1) is not present in the table_array (arg2)

The simple solution here is to use an error handler ending with Resume Next

  1. The formats of arg1 and arg2 are not interpreted correctly

If your lookup_value is a variable you can enclose it with TRIM()

cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)

Who sets response content-type in Spring MVC (@ResponseBody)

Simple declaration of the StringHttpMessageConverter bean is not enough, you need to inject it into AnnotationMethodHandlerAdapter:

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </array>
    </property>
</bean>

However, using this method you have to redefine all HttpMessageConverters, and also it doesn't work with <mvc:annotation-driven />.

So, perhaps the most convenient but ugly method is to intercept instantiation of the AnnotationMethodHandlerAdapter with BeanPostProcessor:

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}

-

<bean class = "EncodingPostProcessor " />

How to set alignment center in TextBox in ASP.NET?

You can use:

<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>

Or this:

textbox.Style["text-align"] = "center"; //right, left

Can you get the number of lines of code from a GitHub repository?

You can run something like

git ls-files | xargs wc -l

which will give you the total count ?

lines of code

Or use this tool ? http://line-count.herokuapp.com/

Relation between CommonJS, AMD and RequireJS?

AMD

  • introduced in JavaScript to scale JavaScript project into multiple files
  • mostly used in browser based application and libraries
  • popular implementation is RequireJS, Dojo Toolkit

CommonJS:

  • it is specification to handle large number of functions, files and modules of big project
  • initial name ServerJS introduced in January, 2009 by Mozilla
  • renamed in August, 2009 to CommonJS to show the broader applicability of the APIs
  • initially implementation were server, nodejs, desktop based libraries

Example

upper.js file

exports.uppercase = str => str.toUpperCase()

main.js file

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

Summary

  • AMD – one of the most ancient module systems, initially implemented by the library require.js.
  • CommonJS – the module system created for Node.js server.
  • UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Resources:

How can I search for a multiline pattern in a file?

Here is the example using GNU grep:

grep -Pzo '_name.*\n.*_description'

-z/--null-data Treat input and output data as sequences of lines.

See also here

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.

The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.

The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

To create both of the created_at and updated_at columns:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

You will need MySQL version >= 5.6.5 to have multiple columns with CURRENT_TIMESTAMP

setImmediate vs. nextTick

In the comments in the answer, it does not explicitly state that nextTick shifted from Macrosemantics to Microsemantics.

before node 0.9 (when setImmediate was introduced), nextTick operated at the start of the next callstack.

since node 0.9, nextTick operates at the end of the existing callstack, whereas setImmediate is at the start of the next callstack

check out https://github.com/YuzuJS/setImmediate for tools and details

Android failed to load JS bundle

The initial question was about reloading the application in a phyisical device.

When you're debugging the application in a physical device (ie via adb), you can reload the JS bundle by clicking on the top left "action" button of your device. This will open the option menu (Reload, Debug JS remotely...).

Hope this helps.

Why does integer division in C# return an integer and not a float?

Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:

int x = 13;
int y = 4;
float x = (float)y / (float)z;

or, if you are using literals:

float x = 13f / 4f;

Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.

How do I print bytes as hexadecimal?

C:

static void print_buf(const char *title, const unsigned char *buf, size_t buf_len)
{
    size_t i = 0;
    fprintf(stdout, "%s\n", title);
    for(i = 0; i < buf_len; ++i)
    fprintf(stdout, "%02X%s", buf[i],
             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

}

C++:

void print_bytes(std::ostream& out, const char *title, const unsigned char *data, size_t dataLen, bool format = true) {
    out << title << std::endl;
    out << std::setfill('0');
    for(size_t i = 0; i < dataLen; ++i) {
        out << std::hex << std::setw(2) << (int)data[i];
        if (format) {
            out << (((i + 1) % 16 == 0) ? "\n" : " ");
        }
    }
    out << std::endl;
}

Auto logout with Angularjs based on idle user

I would like to expand the answers to whoever might be using this in a bigger project, you could accidentally attach multiple event handlers and the program would behave weirdly.

To get rid of that, I used a singleton function exposed by a factory, from which you would call inactivityTimeoutFactory.switchTimeoutOn() and inactivityTimeoutFactory.switchTimeoutOff() in your angular application to respectively activate and deactivate the logout due to inactivity functionality.

This way you make sure you are only running a single instance of the event handlers, no matter how many times you try to activate the timeout procedure, making it easier to use in applications where the user might login from different routes.

Here is my code:

'use strict';

angular.module('YOURMODULENAME')
  .factory('inactivityTimeoutFactory', inactivityTimeoutFactory);

inactivityTimeoutFactory.$inject = ['$document', '$timeout', '$state'];

function inactivityTimeoutFactory($document, $timeout, $state)  {
  function InactivityTimeout () {
    // singleton
    if (InactivityTimeout.prototype._singletonInstance) {
      return InactivityTimeout.prototype._singletonInstance;
    }
    InactivityTimeout.prototype._singletonInstance = this;

    // Timeout timer value
    const timeToLogoutMs = 15*1000*60; //15 minutes
    const timeToWarnMs = 13*1000*60; //13 minutes

    // variables
    let warningTimer;
    let timeoutTimer;
    let isRunning;

    function switchOn () {
      if (!isRunning) {
        switchEventHandlers("on");
        startTimeout();
        isRunning = true;
      }
    }

    function switchOff()  {
      switchEventHandlers("off");
      cancelTimersAndCloseMessages();
      isRunning = false;
    }

    function resetTimeout() {
      cancelTimersAndCloseMessages();
      // reset timeout threads
      startTimeout();
    }

    function cancelTimersAndCloseMessages () {
      // stop any pending timeout
      $timeout.cancel(timeoutTimer);
      $timeout.cancel(warningTimer);
      // remember to close any messages
    }

    function startTimeout () {
      warningTimer = $timeout(processWarning, timeToWarnMs);
      timeoutTimer = $timeout(processLogout, timeToLogoutMs);
    }

    function processWarning() {
      // show warning using popup modules, toasters etc...
    }

    function processLogout() {
      // go to logout page. The state might differ from project to project
      $state.go('authentication.logout');
    }

    function switchEventHandlers(toNewStatus) {
      const body = angular.element($document);
      const trackedEventsList = [
        'keydown',
        'keyup',
        'click',
        'mousemove',
        'DOMMouseScroll',
        'mousewheel',
        'mousedown',
        'touchstart',
        'touchmove',
        'scroll',
        'focus'
      ];

      trackedEventsList.forEach((eventName) => {
        if (toNewStatus === 'off') {
          body.off(eventName, resetTimeout);
        } else if (toNewStatus === 'on') {
          body.on(eventName, resetTimeout);
        }
      });
    }

    // expose switch methods
    this.switchOff = switchOff;
    this.switchOn = switchOn;
  }

  return {
    switchTimeoutOn () {
      (new InactivityTimeout()).switchOn();
    },
    switchTimeoutOff () {
      (new InactivityTimeout()).switchOff();
    }
  };

}

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
    background:red;
    height:50px;
    width:100%;
    position:fixed;
    top:0;
    left:0;    
}.scroller {
    height:300px; 
    overflow:scroll;    
}

List tables in a PostgreSQL schema

Alternatively to information_schema it is possible to use pg_tables:

select * from pg_tables where schemaname='public';

How to show a GUI message box from a bash script in linux?

Everyone mentions zenity, there seem to be many others. A mixed up but interesting list is at http://alternativeto.net/software/zenity/

First, an example of zenity featuring text formatting markup, window title, button label.

zenity \
--info \
--text="<span size=\"xx-large\">Time is $(date +%Hh%M).</span>\n\nGet your <b>coffee</b>." \
--title="Coffee time" \
--ok-label="Sip"

gxmessage

gxmessage "my text"

xmessage

xmessage is very old so it is stable and probably available in all distributions that use X (since it's distributed with X). It is customizable through X resources, for those that have been using Linux or Unix for long enough to know what it means (.Xdefaults, anyone ?).

xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Is xmessage enough for the job ?" -timeout 10

kdialog

(not tested)

In a PPA

YAD: Zenity On Steroids [Display Graphical Dialogs From Shell Scripts] ~ Web Upd8: Ubuntu / Linux blog. Does not seem to auto-size dialogs.

echo My text | yad \
--text-info \
--width=400 \
--height=200

An bigger example

yad \
--title="Desktop entry editor" \
--text="Simple desktop entry editor" \
--form \
--field="Type:CB" \
--field="Name" \
--field="Generic name" \
--field="Comment" \
--field="Command:FL" \
--field="Icon" \
--field="In terminal:CHK" \
--field="Startup notify:CHK" "Application" "Name" "Generic name" "This is the comment" "/usr/bin/yad" "yad" FALSE TRUE \
--button="WebUpd8:2" \
--button="gtk-ok:0" \
--button="gtk-cancel:1"

Others not in Ubuntu standard repositories

  • shellgui
  • xdialog
  • gtkdialog

Off-topic (for terminal)

whiptail --msgbox "my text" 10 20
dialog --msgbox "my text" 10 20

Feel free to edit.

How do I use Notepad++ (or other) with msysgit?

This works for me

git config --global core.editor C:/Progra~1/Notepad++/notepad++.exe

How to pause in C?

If you are making a console window program, you can use system("pause");

SyntaxError: Cannot use import statement outside a module

In my case. I think the problem is in the standard node executable. node target.ts

I replaced it with nodemon and surprisingly it worked!

The way using the standard executable (runner):

node target.ts

The way using the nodemon executable (runner):

nodemon target.ts

Do not forget to install nodemon with npm install nodemon ;P

NOTE: this works amazing for development. But, for runtime, you may execute node with the compiled js file!

Installing specific package versions with pip

I recently ran into an issue when using pip's -I flag that I wanted to document somewhere:

-I will not uninstall the existing package before proceeding; it will just install it on top of the old one. This means that any files that should be deleted between versions will instead be left in place. This can cause weird behavior if those files share names with other installed modules.

For example, let's say there's a package named package. In one of packages files, they use import datetime. Now, in [email protected], this points to the standard library datetime module, but in [email protected], they added a local datetime.py as a replacement for the standard library version (for whatever reason).

Now lets say I run pip install package==3.0.0, but then later realize that I actually wanted version 2.0.0. If I now run pip install -I package==2.0.0, the old datetime.py file will not be removed, so any calls to import datetime will import the wrong module.

In my case, this manifested with strange syntax errors because the newer version of the package added a file that was only compatible with Python 3, and when I downgraded package versions to support Python 2, I continued importing the Python-3-only module.

Based on this, I would argue that uninstalling the old package is always preferable to using -I when updating installed package versions.

Android Horizontal RecyclerView scroll Direction

Try this

I have tried all above answers it's showing me same vertically recycler view, so I have tried another example.

  1. Initialize the adapter

    private Adapter mAdapter;
    
  2. set the adapter like this

    mAdapter = new Adapter();
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
    recycler_view.setLayoutManager(linearLayoutManager);
    recycler_view.setAdapter(mAdapter);
    

Hope this will also work for you For Complete code please refer this link

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

How do you query for "is not null" in Mongo?

db.collection_name.find({"filed_name":{$exists:true}});

fetch documents that contain this filed_name even it is null.

Warning

db.collection_name.find({"filed_name":{$ne:null}});

fetch documents that its field_name has a value $ne to null but this value could be an empty string also.

My proposition:

db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

Darkening an image with CSS (In any shape)

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

C# static class constructor

Static constructor called only the first instance of the class created.

like this:

static class YourClass
{
    static YourClass()
    {
        //initialization
    }
}

pip broke. how to fix DistributionNotFound error?

I had this issue when I was using homebrew. Here is the solution from Issue #26900

python -m pip install --upgrade --force pip

How to force input to only allow Alpha Letters?

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

How to Rotate a UIImage 90 degrees?

Check out the simple and awesome code of Hardy Macia at: cutting-scaling-and-rotating-uiimages

Just call

UIImage *rotatedImage = [originalImage imageRotatedByDegrees:90.0];

Thanks Hardy Macia!

Header:

  • (UIImage *)imageAtRect:(CGRect)rect;
  • (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingToSize:(CGSize)targetSize;
  • (UIImage *)imageRotatedByRadians:(CGFloat)radians;
  • (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

Since the link may die, here's the complete code

//
//  UIImage-Extensions.h
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIImage (CS_Extensions)
- (UIImage *)imageAtRect:(CGRect)rect;
- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
- (UIImage *)imageByScalingToSize:(CGSize)targetSize;
- (UIImage *)imageRotatedByRadians:(CGFloat)radians;
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

@end;

//
//  UIImage-Extensions.m
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//

#import "UIImage-Extensions.h"

CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};

@implementation UIImage (CS_Extensions)

-(UIImage *)imageAtRect:(CGRect)rect
{

   CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
   UIImage* subImage = [UIImage imageWithCGImage: imageRef];
   CGImageRelease(imageRef);

   return subImage;

}

- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor > heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor > heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor < heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor < heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor < heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor > heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   //   CGSize imageSize = sourceImage.size;
   //   CGFloat width = imageSize.width;
   //   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   //   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
   return [self imageRotatedByDegrees:RadiansToDegrees(radians)];
}

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees 
{   
   // calculate the size of the rotated view's containing box for our drawing space
   UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
   CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
   rotatedViewBox.transform = t;
   CGSize rotatedSize = rotatedViewBox.frame.size;
   [rotatedViewBox release];

   // Create the bitmap context
   UIGraphicsBeginImageContext(rotatedSize);
   CGContextRef bitmap = UIGraphicsGetCurrentContext();

   // Move the origin to the middle of the image so we will rotate and scale around the center.
   CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

   //   // Rotate the image context
   CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

   // Now, draw the rotated/scaled image into the context
   CGContextScaleCTM(bitmap, 1.0, -1.0);
   CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);

   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return newImage;

}

@end;

addEventListener for keydown on Canvas

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

Forbidden You don't have permission to access /wp-login.php on this server

This should work :

The instructions says that you add a separate .htaccess containing the lines above to the wp-admin folder - and leave the main .htaccess, in the root, alone.

if that don't help , you can try this:

copy the .htaccess file as is from the wp-admin and placed it in the root folder and bingo! It should work ! if you face new error after this let us know.

for reference you can look here as well:

http://wordpress.org/support/topic/you-dont-have-permission-to-access-blogwp-loginphp-on-this-server

Check using this:

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

In Git, what is the difference between origin/master vs origin master?

Given the fact that you can switch to origin/master (though in detached state) while having your network cable unplugged, it must be a local representation of the master branch at origin.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Or use my solution here www.my-mo.co.uk/device/deviceinfo.php will let you access UDID and email it to whoever you choose too.