Programs & Examples On #Signature

In computer programming, especially object-oriented programming, a method is commonly identified by its unique method signature, which usually includes the method name, and the number, types and order of its parameters. A method signature is the smallest type of a method. The signature tag should not be used to tag questions about digital signatures, email signatures or written signatures.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

It is written here that "By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing."

As it seems that these new checkboxes appeared with Android 2.3, I understand that my previous versions of Android Studio (at least the 2.2) did sign with both signatures. So, to continue as I did before, I think that it is better to check both checkboxes.

EDIT March 31st, 2017 : submitted several apps with both signatures => no problem :)

installation app blocked by play protect

Try to create a new key store and replace with old one, then rebuild a new signed APK.

Update: Note that if you're using a http connection with server ,you should use SSL.

Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies

How to check if a file is empty in Bash?

[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"

Jquery validation plugin - TypeError: $(...).validate is not a function

for me, the problem was from require('jquery-validation') i added in the begging of that js file which Validate method used which is necessary as an npm module

unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes

so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before

Difference between single and double quotes in Bash

The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a as well as an indexed array arr.

If we set

a=apple      # a simple variable
arr=(apple)  # an indexed array with a single element

and then echo the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.

# Expression Result Comments
1 "$a" apple variables are expanded inside ""
2 '$a' $a variables are not expanded inside ''
3 "'$a'" 'apple' '' has no special meaning inside ""
4 '"$a"' "$a" "" is treated literally inside ''
5 '\'' invalid can not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting)
6 "red$arocks" red $arocks does not expand $a; use ${a}rocks to preserve $a
7 "redapple$" redapple$ $ followed by no variable name evaluates to $
8 '\"' \" \ has no special meaning inside ''
9 "\'" \' \' is interpreted inside "" but has no significance for '
10 "\"" " \" is interpreted inside ""
11 "*" * glob does not work inside "" or ''
12 "\t\n" \t\n \t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13 "`echo hi`" hi `` and $() are evaluated inside "" (backquotes are retained in actual output)
14 '`echo hi`' echo hi `` and $() are not evaluated inside '' (backquotes are retained in actual output)
15 '${arr[0]}' ${arr[0]} array access not possible inside ''
16 "${arr[0]}" apple array access works inside ""
17 $'$a\'' $a' single quotes can be escaped inside ANSI-C quoting
18 "$'\t'" $'\t' ANSI-C quoting is not interpreted inside ""
19 '!cmd' !cmd history expansion character '!' is ignored inside ''
20 "!cmd" cmd args expands to the most recent command matching "cmd"
21 $'!cmd' !cmd history expansion character '!' is ignored inside ANSI-C quotes

See also:

Determine device (iPhone, iPod Touch) with iOS

I know an answer has been ticked already, but for future reference, you could always use the device screen size to figure out which device it is like so:

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

    CGSize result = [[UIScreen mainScreen] bounds].size;

    if (result.height == 480) {
        // 3.5 inch display - iPhone 4S and below
        NSLog(@"Device is an iPhone 4S or below");
    }

    else if (result.height == 568) {
        // 4 inch display - iPhone 5
        NSLog(@"Device is an iPhone 5/S/C");
    }

    else if (result.height == 667) {
        // 4.7 inch display - iPhone 6
        NSLog(@"Device is an iPhone 6");
    }

    else if (result.height == 736) {
        // 5.5 inch display - iPhone 6 Plus
        NSLog(@"Device is an iPhone 6 Plus");
    }
} 

else if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
       // iPad 9.7 or 7.9 inch display.
       NSLog(@"Device is an iPad.");
}

Save multiple sheets to .pdf

Start by selecting the sheets you want to combine:

ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
     IgnorePrintAreas:=False, OpenAfterPublish:=True

Installing tensorflow with anaconda in windows

The above steps

conda install -c conda-forge tensorflow

will work for Windows 10 as well but the Python version should be 3.5 or above. I have used it with Anaconda Python version 3.6 as the protocol buffer format it refers to available on 3.5 or above. Thanks, Sandip

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

Java 8: Lambda-Streams, Filter by Method with Exception

Extending @marcg solution, you can normally throw and catch a checked exception in Streams; that is, compiler will ask you to catch/re-throw as is you were outside streams!!

@FunctionalInterface
public interface Predicate_WithExceptions<T, E extends Exception> {
    boolean test(T t) throws E;
}

/**
 * .filter(rethrowPredicate(t -> t.isActive()))
 */
public static <T, E extends Exception> Predicate<T> rethrowPredicate(Predicate_WithExceptions<T, E> predicate) throws E {
    return t -> {
        try {
            return predicate.test(t);
        } catch (Exception exception) {
            return throwActualException(exception);
        }
    };
}

@SuppressWarnings("unchecked")
private static <T, E extends Exception> T throwActualException(Exception exception) throws E {
    throw (E) exception;
}

Then, your example would be written as follows (adding tests to show it more clearly):

@Test
public void testPredicate() throws MyTestException {
    List<String> nonEmptyStrings = Stream.of("ciao", "")
            .filter(rethrowPredicate(s -> notEmpty(s)))
            .collect(toList());
    assertEquals(1, nonEmptyStrings.size());
    assertEquals("ciao", nonEmptyStrings.get(0));
}

private class MyTestException extends Exception { }

private boolean notEmpty(String value) throws MyTestException {
    if(value==null) {
        throw new MyTestException();
    }
    return !value.isEmpty();
}

@Test
public void testPredicateRaisingException() throws MyTestException {
    try {
        Stream.of("ciao", null)
                .filter(rethrowPredicate(s -> notEmpty(s)))
                .collect(toList());
        fail();
    } catch (MyTestException e) {
        //OK
    }
}

iOS9 Untrusted Enterprise Developer with no option to trust

Device: iPad Mini

OS: iOS 9 Beta 3

App downloaded from: Hockey App

Provisioning profile with Trust issues: Enterprise

In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.

Settings>General>Profile

Here are the steps that I followed:

  1. Connect the Device
  2. Open Xcode
  3. Navigate to Window > Devices
  4. Right click on the Device and select Show Provisioning Profiles...
  5. Delete your Enterprise provisioning profile. Hit Done. Window>Device>Provisioning Profile
  6. Open HockeyApp. Install your app.
  7. Once the app finished installing, go back to Settings>General>Profiles. You should now be able to see your Enterprise provisioning profile. enter image description here
  8. Click Trust enter image description here

That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)

Edit Crystal report file without Crystal Report software

In case anyone else is looking for this... as of April 2013, you can still get the free Visual Studio edition of Crystal Reports from this web site: SAP Crystal Reports - Downloads (updated url).

It installs into Visual Studio 2010 or VS 2012, and you can edit and save RPT files with as much capability as the standard Crystal Reports editor.

Javascript: The prettiest way to compare one value against multiple values

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):

(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}

How to tell a Mockito mock object to return something different the next time it is called?

Or, even cleaner:

when(mockFoo.someMethod()).thenReturn(obj1, obj2);

Get a Windows Forms control by name in C#

You can use find function in your Form class. If you want to cast (Label) ,(TextView) ... etc, in this way you can use special features of objects. It will be return Label object.

(Label)this.Controls.Find(name,true)[0];

name: item name of searched item in the form

true: Search all Children boolean value

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

TimePicker Dialog from clicking EditText

For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog . how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?

          // perform click event on edit text
            dpFlightDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // calender class's instance and get current date , month and year from calender
                    final Calendar c = Calendar.getInstance();
                    int mYear = c.get(Calendar.YEAR); // current year
                    int mMonth = c.get(Calendar.MONTH); // current month
                    int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
                    // date picker dialog
                    datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year,
                                                      int monthOfYear, int dayOfMonth) {
                                    // set day of month , month and year value in the edit text
                                    dpFlightDate.setText(dayOfMonth + "/"
                                            + (monthOfYear + 1) + "/" + year);

                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();
                }
            });
            tpFlightTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Use the current time as the default values for the picker
                    final Calendar c = Calendar.getInstance();
                    int hour = c.get(Calendar.HOUR_OF_DAY);
                    int minute = c.get(Calendar.MINUTE);
                    // Create a new instance of TimePickerDialog
                    timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            tpFlightTime.setText( selectedHour + ":" + selectedMinute);
                        }
                    }, hour, minute, true);//Yes 24 hour time
                    timePickerDialog.setTitle("Select Time");
                    timePickerDialog.show();
                }
            });

Why does instanceof return false for some literals?

https://www.npmjs.com/package/typeof

Returns a string-representation of instanceof (the constructors name)

function instanceOf(object) {
  var type = typeof object

  if (type === 'undefined') {
    return 'undefined'
  }

  if (object) {
    type = object.constructor.name
  } else if (type === 'object') {
    type = Object.prototype.toString.call(object).slice(8, -1)
  }

  return type.toLowerCase()
}

instanceOf(false)                  // "boolean"
instanceOf(new Promise(() => {}))  // "promise"
instanceOf(null)                   // "null"
instanceOf(undefined)              // "undefined"
instanceOf(1)                      // "number"
instanceOf(() => {})               // "function"
instanceOf([])                     // "array"

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

How to avoid Number Format Exception in java?

one posibility: catch the exception and show an error message within the user frontend.

edit: add an listener to the field within the gui and check the user inputs there too, with this solution the exception case should be very rare...

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

Move an item inside a list?

A slightly shorter solution, that only moves the item to the end, not anywhere is this:

l += [l.pop(0)]

For example:

>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]

How can I properly use a PDO object for a parameterized SELECT query

A litle bit complete answer is here with all ready for use:

    $sql = "SELECT `username` FROM `users` WHERE `id` = :id";
    $q = $dbh->prepare($sql);
    $q->execute(array(':id' => "4"));
    $done= $q->fetch();

 echo $done[0];

Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();

I hope this help someone, Enjoy!

Adjust icon size of Floating action button (fab)

If you are using androidx 1.0.0 and are using a custom fab size, you will have to specify the custom size using

app:fabCustomSize="your custom size in dp"

By deafult the size is 56dp and there is another variation that is the small sized fab which is 40dp, if you are using anything you will have to specify it for the padding to be calculated correctly

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

SOLVING

Address already in use — bind(2)” 500 error in Ruby on Rails

Recently I tried running a Rails app on a production server. Not only did it not work, but it broke my localhost:3000 development server as well. Localhost would only load a blank white page or a 500 error.

To solve this, I used two quick commands. If these don’t return a result, you may need to look elsewhere for a solution, but this is a good quick fix.

lsof -wni tcp:3000


ruby    52179 rachelchervin   50u  IPv6 0x...7aa3      0t0  TCP [::1]:hbci (LISTEN)
ruby    52179 rachelchervin   51u  IPv4 0x...c7bb      0t0  TCP 127.0.0.1:hbci (LISTEN)
ruby    52180 rachelchervin   50u  IPv6 0x...7aa3      0t0  TCP [::1]:hbci (LISTEN)
ruby    52180 rachelchervin   51u  IPv4 0x...c7bb      0t0  TCP 127.0.0.1:hbci (LISTEN)

This command shows all of my currently running processes and their PIDs (process IDs) on the 3000 port. Because there are existing running processes that did not close correctly, my new :3000 server can’t start, hence the 500 error.

kill 52179

kill 52180

rails s

I used the Linux kill command to manually stop the offending processes. If you have more than 4, simply use kill on any PIDs until the first command comes back blank. Then, try restarting your localhost:3000 server again. This will not damage your computer! It simply kills existing ruby processes on your localhost port. A new server will start these processes all over again. Good luck!

What is the difference between bindParam and bindValue?

From the manual entry for PDOStatement::bindParam:

[With bindParam] Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

So, for example:

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'

or

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'

How to extract the n-th elements from a list of tuples?

This also works:

zip(*elements)[1]

(I am mainly posting this, to prove to myself that I have groked zip...)

See it in action:

>>> help(zip)

Help on built-in function zip in module builtin:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> zip(*elements)
[(1, 2, 3), (1, 3, 5), (1, 7, 10)]
>>> zip(*elements)[1]
(1, 3, 5)
>>>

Neat thing I learned today: Use *list in arguments to create a parameter list for a function...

Note: In Python3, zip returns an iterator, so instead use list(zip(*elements)) to return a list of tuples.

How do I launch a Git Bash window with particular working directory using a script?

In addition, Win10 gives you an option to open git bash from your working directory by right-clicking on your folder and selecting GitBash here.

enter image description here

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

In other words mkdir() is like mkdir and mkdirs() is like mkdir -p.

For example, imagine we have an empty /tmp directory. The following code

new File("/tmp/one/two/three").mkdirs();

would create the following directories:

  • /tmp/one
  • /tmp/one/two
  • /tmp/one/two/three

Where this code:

new File("/tmp/one/two/three").mkdir();

would not create any directories - as it wouldn't find /tmp/one/two - and would return false.

ISO C90 forbids mixed declarations and code in C

-Wdeclaration-after-statement minimal reproducible example

main.c

#!/usr/bin/env bash

set -eux

cat << EOF > main.c
#include <stdio.h>

int main(void) {
    puts("hello");
    int a = 1;
    printf("%d\n", a);
    return 0;
}
EOF

Give warning:

gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c

Don't give warning:

gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c

The warning:

main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     int a = 1;
     ^~~

Tested on Ubuntu 16.04, GCC 6.4.0.

PowerShell and the -contains operator

-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient.

The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.

Doing a cleanup action just before Node.js exits

In the case where the process was spawned by another node process, like:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',
});

And you try to kill it later, via:

child.kill();

This is how you handle the event [on the child]:

process.on('SIGTERM', function() {
    console.log('Goodbye!');
});

How do you convert Html to plain text?

If you have data that has HTML tags and you want to display it so that a person can SEE the tags, use HttpServerUtility::HtmlEncode.

If you have data that has HTML tags in it and you want the user to see the tags rendered, then display the text as is. If the text represents an entire web page, use an IFRAME for it.

If you have data that has HTML tags and you want to strip out the tags and just display the unformatted text, use a regular expression.

Why use the INCLUDE clause when creating an index?

This discussion is missing out on the important point: The question is not if the "non-key-columns" are better to include as index-columns or as included-columns.

The question is how expensive it is to use the include-mechanism to include columns that are not really needed in index? (typically not part of where-clauses, but often included in selects). So your dilemma is always:

  1. Use index on id1, id2 ... idN alone or
  2. Use index on id1, id2 ... idN plus include col1, col2 ... colN

Where: id1, id2 ... idN are columns often used in restrictions and col1, col2 ... colN are columns often selected, but typically not used in restrictions

(The option to include all of these columns as part of the index-key is just always silly (unless they are also used in restrictions) - cause it would always be more expensive to maintain since the index must be updated and sorted even when the "keys" have not changed).

So use option 1 or 2?

Answer: If your table is rarely updated - mostly inserted into/deleted from - then it is relatively inexpensive to use the include-mechanism to include some "hot columns" (that are often used in selects - but not often used on restrictions) since inserts/deletes require the index to be updated/sorted anyway and thus little extra overhead is associated with storing off a few extra columns while already updating the index. The overhead is the extra memory and CPU used to store redundant info on the index.

If the columns you consider to add as included-columns are often updated (without the index-key-columns being updated) - or - if it is so many of them that the index becomes close to a copy of your table - use option 1 I'd suggest! Also if adding certain include-column(s) turns out to make no performance-difference - you might want to skip the idea of adding them:) Verify that they are useful!

The average number of rows per same values in keys (id1, id2 ... idN) can be of some importance as well.

Notice that if a column - that is added as an included-column of index - is used in the restriction: As long as the index as such can be used (based on restriction against index-key-columns) - then SQL Server is matching the column-restriction against the index (leaf-node-values) instead of going the expensive way around the table itself.

"Unable to launch the IIS Express Web server" error

Deleting the unnecessary site entries from applicationhost.config file solved the issue for me.

How to convert Varchar to Int in sql server 2008?

That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.

If you have any NULL values, use

ISNULL(column1, 0)

How to define hash tables in Bash?

A coworker just mentioned this thread. I've independently implemented hash tables within bash, and it's not dependent on version 4. From a blog post of mine in March 2010 (before some of the answers here...) entitled Hash tables in bash:

I previously used cksum to hash but have since translated Java's string hashCode to native bash/zsh.

# Here's the hashing function
ht() {
  local h=0 i
  for (( i=0; i < ${#1}; i++ )); do
    let "h=( (h<<5) - h ) + $(printf %d \'${1:$i:1})"
    let "h |= h"
  done
  printf "$h"
}

# Example:

myhash[`ht foo bar`]="a value"
myhash[`ht baz baf`]="b value"

echo ${myhash[`ht baz baf`]} # "b value"
echo ${myhash[@]} # "a value b value" though perhaps reversed
echo ${#myhash[@]} # "2" - there are two values (note, zsh doesn't count right)

It's not bidirectional, and the built-in way is a lot better, but neither should really be used anyway. Bash is for quick one-offs, and such things should quite rarely involve complexity that might require hashes, except perhaps in your ~/.bashrc and friends.

dropping a global temporary table

-- First Truncate temporary table
SQL> TRUNCATE TABLE test_temp1;

-- Then Drop temporary table
SQL> DROP TABLE test_temp1;

How To Remove Outline Border From Input Button

Given the html below:

<button class="btn-without-border"> Submit </button>

In the css style do the following:

.btn-without-border:focus {
    border: none;
    outline: none;
}

This code will remove button border and will disable button border focus when the button is clicked.

Replace part of a string with another string

To have the new string returned use this:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

Restart pods when configmap updates in Kubernetes?

https://github.com/kubernetes/helm/blob/master/docs/charts_tips_and_tricks.md#user-content-automatically-roll-deployments-when-configmaps-or-secrets-change

Often times configmaps or secrets are injected as configuration files in containers. Depending on the application a restart may be required should those be updated with a subsequent helm upgrade, but if the deployment spec itself didn't change the application keeps running with the old configuration resulting in an inconsistent deployment.

The sha256sum function can be used together with the include function to ensure a deployments template section is updated if another spec changes:

kind: Deployment
spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
[...]

In my case, for some reasons, $.Template.BasePath didn't work but $.Chart.Name does:

spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: admin-app
      annotations:
        checksum/config: {{ include (print $.Chart.Name "/templates/" $.Chart.Name "-configmap.yaml") . | sha256sum }}

Is it possible to open developer tools console in Chrome on Android phone?

When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)

Best way to compare two complex objects

Use IEquatable<T> Interface which has a method Equals.

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

How to send json data in the Http request using NSURLRequest

I struggled with this for a while. Running PHP on the server. This code will post a json and get the json reply from the server

NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil){
         NSError *parseError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }
     else if ([data length] == 0 && error == nil){
         NSLog(@"no data returned");
         //no data, but tried
     }
     else if (error != nil)
     {
         NSLog(@"there was a download error");
         //couldn't download

     }
 }];

How to update Identity Column in SQL Server?

DBCC CHECKIDENT(table_name, RESEED, value)

table_name = give the table you want to reset value

value=initial value to be zero,to start identity column with 1

Random Number Between 2 Double Numbers

Use a static Random or the numbers tend to repeat in tight/fast loops due to the system clock seeding them.

public static class RandomNumbers
{
    private static Random random = new Random();
    //=-------------------------------------------------------------------
    // double between min and the max number
    public static double RandomDouble(int min, int max) 
    {
        return (random.NextDouble() * (max - min)) + min;
    }
    //=----------------------------------
    // double between 0 and the max number
    public static double RandomDouble(int max) 
    {
        return (random.NextDouble() * max);
    }
    //=-------------------------------------------------------------------
    // int between the min and the max number
    public static int RandomInt(int min, int max) 
    {   
        return random.Next(min, max + 1);
    }
    //=----------------------------------
    // int between 0 and the max number
    public static int RandomInt(int max) 
    {
        return random.Next(max + 1);
    }
    //=-------------------------------------------------------------------
 }

See also : https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8

Accessing items in an collections.OrderedDict by index

It is dramatically more efficient to use IndexedOrderedDict from the indexed package.

Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.

In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop

In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop

IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.

T-SQL stored procedure that accepts multiple Id values

A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :

Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))

All credit goes to Guru Brad Schulz's Blog

Multiple arguments to function called by pthread_create()?

main() has it's own thread and stack variables. either allocate memory for 'args' in the heap or make it global:

struct arg_struct {
    int arg1;
    int arg2;
}args;

//declares args as global out of main()

Then of course change the references from args->arg1 to args.arg1 etc..

How do I list / export private keys from a keystore?

First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.

Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt option of its pkcs8 utility):

KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
  String alias = aliases.nextElement();
  if (!keys.isKeyEntry(alias))
    continue;
  Key key = keys.getKey(alias, password);
  if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
    /* Most PrivateKeys use this format, but check for safety. */
    try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
      os.write(key.getEncoded());
      os.flush();
    }
  }
}

If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.

What is the purpose of the "role" attribute in HTML?

I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:

Warning: The form role is unnecessary for element form.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

If you happen to be using the amqplib library as I am, they have a handy example of an implementation of the Publish/Subscribe RabbitMQ tutorial which you might find handy.

Calculate time difference in Windows batch file

Aacini's latest code showcases an awesome variable substitution method.
It's a shame it's not Regional format proof - it fails on so many levels.
Here's a short fix that keeps the substitution+math method intact:

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%" & rem AveYo: fix single digit hour

set /P "=Any process here..."

set "endTime=%time: =0%" & rem AveYo: fix single digit hour

rem Aveyo: Regional format fix with just one aditional line
for /f "tokens=1-3 delims=0123456789" %%i in ("%endTime%") do set "COLON=%%i" & set "DOT=%%k" 

rem Get elapsed time:
set "end=!endTime:%DOT%=%%100)*100+1!" & set "start=!startTime:%DOT%=%%100)*100+1!"
set /A "elap=((((10!end:%COLON%=%%100)*60+1!%%100)-((((10!start:%COLON%=%%100)*60+1!%%100)"

rem Aveyo: Fix 24 hours 
set /A "elap=!elap:-=8640000-!"

rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"

echo Start:    %startTime%
echo End:      %endTime%
echo Elapsed:  %hh:~1%%COLON%%mm:~1%%COLON%%ss:~1%%DOT%%cc:~1% & rem AveYo: display as regional
pause

*

"Lean and Mean" TIMER with Regional format, 24h and mixed input support
Adapting Aacini's substitution method body, no IF's, just one FOR (my regional fix)

1: File timer.bat placed somewhere in %PATH% or the current dir

@echo off & rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

Usage:
timer & echo start_cmds & timeout /t 3 & echo end_cmds & timer
timer & timer "23:23:23,00"
timer "23:23:23,00" & timer
timer "13.23.23,00" & timer "03:03:03.00"
timer & timer "0:00:00.00" no & cmd /v:on /c echo until midnight=!timer_end!
Input can now be mixed, for those unlikely, but possible time format changes during execution

2: Function :timer bundled with the batch script (sample usage below):

@echo off
set "TIMER=call :timer" & rem short macro
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process here..
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER% 
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~ end
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no 
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause 
exit /b

:: to test it, copy-paste both above and below code sections

rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support 
:timer Usage " call :timer [input - optional] [no - optional]" :i Result printed on second call, saved to timer_end 
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

What are projection and selection?

Projection: what ever typed in select clause i.e, 'column list' or '*' or 'expressions' that becomes under projection.

*selection:*what type of conditions we are applying on that columns i.e, getting the records that comes under selection.

For example:

  SELECT empno,ename,dno,job from Emp 
     WHERE job='CLERK'; 

in the above query the columns "empno,ename,dno,job" those comes under projection, "where job='clerk'" comes under selection

2 column div layout: right column with fixed width, left fluid

Simplest and most flexible solution so far it to use table display:

HTML, left div comes first, right div comes second ... we read and write left to right, so it won't make any sense to place the divs right to left

<div class="container">
    <div class="left">
        left content flexible width
    </div>
    <div class="right">
        right content fixed width
    </div>
</div>

CSS:

.container {
  display: table;
  width: 100%;
}

.left {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}??

.right {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}

Cases examples:

// One div is 150px fixed width ; the other takes the rest of the width
.left {width: 150px} .right {width: 100%}

// One div is auto to its inner width ; the other takes the rest of the width
.left {width: 100%} .right {width: auto}

foreach vs someList.ForEach(){}

I know two obscure-ish things that make them different. Go me!

Firstly, there's the classic bug of making a delegate for each item in the list. If you use the foreach keyword, all your delegates can end up referring to the last item of the list:

    // A list of actions to execute later
    List<Action> actions = new List<Action>();

    // Numbers 0 to 9
    List<int> numbers = Enumerable.Range(0, 10).ToList();

    // Store an action that prints each number (WRONG!)
    foreach (int number in numbers)
        actions.Add(() => Console.WriteLine(number));

    // Run the actions, we actually print 10 copies of "9"
    foreach (Action action in actions)
        action();

    // So try again
    actions.Clear();

    // Store an action that prints each number (RIGHT!)
    numbers.ForEach(number =>
        actions.Add(() => Console.WriteLine(number)));

    // Run the actions
    foreach (Action action in actions)
        action();

The List.ForEach method doesn't have this problem. The current item of the iteration is passed by value as an argument to the outer lambda, and then the inner lambda correctly captures that argument in its own closure. Problem solved.

(Sadly I believe ForEach is a member of List, rather than an extension method, though it's easy to define it yourself so you have this facility on any enumerable type.)

Secondly, the ForEach method approach has a limitation. If you are implementing IEnumerable by using yield return, you can't do a yield return inside the lambda. So looping through the items in a collection in order to yield return things is not possible by this method. You'll have to use the foreach keyword and work around the closure problem by manually making a copy of the current loop value inside the loop.

More here

What is the most efficient way to get first and last line of a text file?

This is my solution, compatible also with Python3. It does also manage border cases, but it misses utf-16 support:

def tail(filepath):
    """
    @author Marco Sulla ([email protected])
    @date May 31, 2016
    """

    try:
        filepath.is_file
        fp = str(filepath)
    except AttributeError:
        fp = filepath

    with open(fp, "rb") as f:
        size = os.stat(fp).st_size
        start_pos = 0 if size - 1 < 0 else size - 1

        if start_pos != 0:
            f.seek(start_pos)
            char = f.read(1)

            if char == b"\n":
                start_pos -= 1
                f.seek(start_pos)

            if start_pos == 0:
                f.seek(start_pos)
            else:
                char = ""

                for pos in range(start_pos, -1, -1):
                    f.seek(pos)

                    char = f.read(1)

                    if char == b"\n":
                        break

        return f.readline()

It's ispired by Trasp's answer and AnotherParker's comment.

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

Adding a column to a data.frame

I believe that using "cbind" is the simplest way to add a column to a data frame in R. Below an example:

    myDf = data.frame(index=seq(1,10,1), Val=seq(1,10,1))
    newCol= seq(2,20,2)
    myDf = cbind(myDf,newCol)

How to round a number to n decimal places in Java

You can use the DecimalFormat class.

double d = 3.76628729;

DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal =  Double.valueOf(newFormat.format(d));

Google Chrome "window.open" workaround?

The other answers are outdated. The behavior of Chrome for window.open depends on where it is called from. See also this topic.

When window.open is called from a handler that was triggered though a user action (e.g. onclick event), it will behave similar as <a target="_blank">, which by default opens in a new tab. However if window.open is called elsewhere, Chrome ignores other arguments and always opens a new window with a non-editable address bar.

This looks like some kind of security measure, although the rationale behind it is not completely clear.

Cannot open new Jupyter Notebook [Permission Denied]

In windows, I copied, what I think is a snapshot:

.~SomeAmazingNotebook.ipynb

renamed it:

SomeAmazingNotebook.ipynb

and could open it.

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

MySQL, update multiple tables with one query

Take the case of two tables, Books and Orders. In case, we increase the number of books in a particular order with Order.ID = 1002 in Orders table then we also need to reduce that the total number of books available in our stock by the same number in Books table.

UPDATE Books, Orders
SET Orders.Quantity = Orders.Quantity + 2,
    Books.InStock = Books.InStock - 2
WHERE
    Books.BookID = Orders.BookID
    AND Orders.OrderID = 1002;

"401 Unauthorized" on a directory

  1. Open IIS and select site that is causing 401
  2. Select Authentication property in IIS Header
  3. Select Anonymous Authentication
  4. Right click on it, select Edit and choose Application pool identity
  5. Restart site and it should work

How can a Java program get its own process ID?

There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.

On linux+windows it returns a value like 12345@hostname (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:

Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

In Java 9 the new process API can be used:

long pid = ProcessHandle.current().pid();

Java reverse an int value without using array

A method to get the greatest power of ten smaller or equal to an integer: (in recursion)

public static int powerOfTen(int n) {
    if ( n < 10)
        return 1;
    else
        return 10 * powerOfTen(n/10); 
}

The method to reverse the actual integer:(in recursion)

public static int reverseInteger(int i) {
    if (i / 10 < 1)
        return i ;
    else
        return i%10*powerOfTen(i) + reverseInteger(i/10);
}

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

how to check if object already exists in a list

Another point to mention is that you should ensure that your equality function is as you expect. You should override the equals method to set up what properties of your object have to match for two instances to be considered equal.

Then you can just do mylist.contains(item)

Gradle error: could not execute build using gradle distribution

I entered: [C:\Users\user\].gradle\caches\1.8\scripts directory and deleted its content. I didn't had to restart anything, just removed scripts content any rerun it.

How to manually set an authenticated user in Spring Security / SpringMVC

Ultimately figured out the root of the problem.

When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).

At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.

Is there a function to make a copy of a PHP array to another?

I know this as long time ago, but this worked for me..

$copied_array = array_slice($original_array,0,count($original_array));

Razor View throwing "The name 'model' does not exist in the current context"

I solved the problem by using @Model instead of just model when printing the variables.

How to style a JSON block in Github Wiki?

You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

Common sources of unterminated string literal

Have you tried Chromebug? It's the Firebug for extensions.

Why does pycharm propose to change method to static

Since you didn't refer to self in the bar method body, PyCharm is asking if you might have wanted to make bar static. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that's your only reason, you're probably better off going with a top-level function - as note here.

In short, I'm not one hundred percent sure why it's there. I'm guessing they'll probably remove it in an upcoming release.

How to check if my string is equal to null?

If you are working in Android then you can use the simple TextUtils class. Check the following code:

if(!TextUtils.isEmpty(myString)){
 //do something
}

This is simple usage of code. Answer may be repeated. But is simple to have single and simple check for you.

Copy folder recursively, excluding some folders

you can use tar, with --exclude option , and then untar it in destination. eg

cd /source_directory
tar cvf test.tar --exclude=dir_to_exclude *
mv test.tar /destination 
cd /destination  
tar xvf test.tar

see the man page of tar for more info

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).

==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.

I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!

Hope this helps to make things even clearer!

enter image description here

Why are iframes considered dangerous and a security risk?

"Dangerous" and "Security risk" are not the first things that spring to mind when people mention iframes … but they can be used in clickjacking attacks.

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

Converting DateTime format using razor

The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor. I got it working by doing the following,

Model:

[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }

View:

        <div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
            @Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
            <span class="indicator"></span>
            @Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
            <span id="validEmail"></span>
            <br />
            @Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
        </div>

Output: 30/12/2011

Related link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.applyformatineditmode.aspx

Input group - two inputs close to each other

working workaround:

<div class="input-group">
    <input type="text" class="form-control input-sm" value="test1" />
    <span class="input-group-btn" style="width:0px;"></span>
    <input type="text" class="form-control input-sm" value="test2" />
</div>

downside: no border-collapse between the two text-fields, but they keep next to each other

http://jsfiddle.net/EfC26/

Update

thanks to Stalinko

This technique allows to glue more than 2 inputs. Border-collapsing is achieved using "margin-left: -1px" (-2px for the 3rd input and so on)

<div class="input-group">
  <input type="text" class="form-control input-sm" value="test1" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-1px" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-2px" />
</div>

http://jsfiddle.net/yLvk5mn1/1/

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

Using Vim's tabs like buffers

Stop, stop, stop.

This is not how Vim's tabs are designed to be used. In fact, they're misnamed. A better name would be "viewport" or "layout", because that's what a tab is—it's a different layout of windows of all of your existing buffers.

Trying to beat Vim into 1 tab == 1 buffer is an exercise in futility. Vim doesn't know or care and it will not respect it on all commands—in particular, anything that uses the quickfix buffer (:make, :grep, and :helpgrep are the ones that spring to mind) will happily ignore tabs and there's nothing you can do to stop that.

Instead:

  • :set hidden
    If you don't have this set already, then do so. It makes vim work like every other multiple-file editor on the planet. You can have edited buffers that aren't visible in a window somewhere.
  • Use :bn, :bp, :b #, :b name, and ctrl-6 to switch between buffers. I like ctrl-6 myself (alone it switches to the previously used buffer, or #ctrl-6 switches to buffer number #).
  • Use :ls to list buffers, or a plugin like MiniBufExpl or BufExplorer.

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

I want my android application to be only run in portrait mode?

There are two ways,

  1. Add android:screenOrientation="portrait" for each Activity in Manifest File
  2. Add this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); in each java file.

Declaring a custom android UI element using XML

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here

Converting int to string in C

Similar implementation to Ahmad Sirojuddin but slightly different semantics. From a security perspective, any time a function writes into a string buffer, the function should really "know" the size of the buffer and refuse to write past the end of it. I would guess its a part of the reason you can't find itoa anymore.

Also, the following implementation avoids performing the module/devide operation twice.

char *u32todec( uint32_t    value,
                char        *buf,
                int         size)
{
    if(size > 1){
        int i=size-1, offset, bytes;
        buf[i--]='\0';
        do{
            buf[i--]=(value % 10)+'0';
            value = value/10;
        }while((value > 0) && (i>=0));
        offset=i+1;
        if(offset > 0){
            bytes=size-i-1;
            for(i=0;i<bytes;i++)
                buf[i]=buf[i+offset];
        }
        return buf;
    }else
        return NULL;
}

The following code both tests the above code and demonstrates its correctness:

int main(void)
{
    uint64_t acc;
    uint32_t inc;
    char buf[16];
    size_t bufsize;
    for(acc=0, inc=7; acc<0x100000000; acc+=inc){
        printf("%u: ", (uint32_t)acc);
        for(bufsize=17; bufsize>0; bufsize/=2){
            if(NULL != u32todec((uint32_t)acc, buf, bufsize))
                printf("%s ", buf);
        }
        printf("\n");
        if(acc/inc > 9)
            inc*=7;
    }
    return 0;
}

Python: list of lists

First, I strongly recommend that you rename your variable list to something else. list is the name of the built-in list constructor, and you're hiding its normal function. I will rename list to a in the following.

Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a it's referring to the same actual list object as last time. So when you call

listoflists.append((a, a[0]))

you can later change a and it changes what the first element of that tuple points to. This does not happen with a[0] because the object (which is an integer) pointed to by a[0] doesn't change (although a[0] points to different objects over the run of your code).

You can create a copy of the whole list a using the list constructor:

listoflists.append((list(a), a[0]))

Or, you can use the slice notation to make a copy:

listoflists.append((a[:], a[0]))

Replace all whitespace characters

Try this:

str.replace(/\s/g, "X")

Can I force a page break in HTML printing?

Try this link

<style>
@media print
{
h1 {page-break-before:always}
}
</style>

Named capturing groups in JavaScript regex?

Naming captured groups provide one thing: less confusion with complex regular expressions.

It really depends on your use-case but maybe pretty-printing your regex could help.

Or you could try and define constants to refer to your captured groups.

Comments might then also help to show others who read your code, what you have done.

For the rest I must agree with Tims answer.

Rails: How to list database tables/objects using the Rails console?

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

HTML display result in text (input) field?

 <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>

      </BODY>
</HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

How to change the cursor into a hand when a user hovers over a list item?

Use for li:

li:hover {
    cursor: pointer;
}

See more cursor properties with examples after running snippet option:

An animation showing a cursor hovering over a div of each class

_x000D_
_x000D_
.auto          { cursor: auto; }_x000D_
.default       { cursor: default; }_x000D_
.none          { cursor: none; }_x000D_
.context-menu  { cursor: context-menu; }_x000D_
.help          { cursor: help; }_x000D_
.pointer       { cursor: pointer; }_x000D_
.progress      { cursor: progress; }_x000D_
.wait          { cursor: wait; }_x000D_
.cell          { cursor: cell; }_x000D_
.crosshair     { cursor: crosshair; }_x000D_
.text          { cursor: text; }_x000D_
.vertical-text { cursor: vertical-text; }_x000D_
.alias         { cursor: alias; }_x000D_
.copy          { cursor: copy; }_x000D_
.move          { cursor: move; }_x000D_
.no-drop       { cursor: no-drop; }_x000D_
.not-allowed   { cursor: not-allowed; }_x000D_
.all-scroll    { cursor: all-scroll; }_x000D_
.col-resize    { cursor: col-resize; }_x000D_
.row-resize    { cursor: row-resize; }_x000D_
.n-resize      { cursor: n-resize; }_x000D_
.e-resize      { cursor: e-resize; }_x000D_
.s-resize      { cursor: s-resize; }_x000D_
.w-resize      { cursor: w-resize; }_x000D_
.ns-resize     { cursor: ns-resize; }_x000D_
.ew-resize     { cursor: ew-resize; }_x000D_
.ne-resize     { cursor: ne-resize; }_x000D_
.nw-resize     { cursor: nw-resize; }_x000D_
.se-resize     { cursor: se-resize; }_x000D_
.sw-resize     { cursor: sw-resize; }_x000D_
.nesw-resize   { cursor: nesw-resize; }_x000D_
.nwse-resize   { cursor: nwse-resize; }_x000D_
_x000D_
.cursors > div {_x000D_
    float: left;_x000D_
    box-sizing: border-box;_x000D_
    background: #f2f2f2;_x000D_
    border:1px solid #ccc;_x000D_
    width: 20%;_x000D_
    padding: 10px 2px;_x000D_
    text-align: center;_x000D_
    white-space: nowrap;_x000D_
    &:nth-child(even) {_x000D_
       background: #eee;_x000D_
    }_x000D_
    &:hover {_x000D_
       opacity: 0.25_x000D_
    }_x000D_
}
_x000D_
<h1>Example of cursor</h1>_x000D_
_x000D_
<div class="cursors">_x000D_
    <div class="auto">auto</div>_x000D_
    <div class="default">default</div>_x000D_
    <div class="none">none</div>_x000D_
    <div class="context-menu">context-menu</div>_x000D_
    <div class="help">help</div>_x000D_
    <div class="pointer">pointer</div>_x000D_
    <div class="progress">progress</div>_x000D_
    <div class="wait">wait</div>_x000D_
    <div class="cell">cell</div>_x000D_
    <div class="crosshair">crosshair</div>_x000D_
    <div class="text">text</div>_x000D_
    <div class="vertical-text">vertical-text</div>_x000D_
    <div class="alias">alias</div>_x000D_
    <div class="copy">copy</div>_x000D_
    <div class="move">move</div>_x000D_
    <div class="no-drop">no-drop</div>_x000D_
    <div class="not-allowed">not-allowed</div>_x000D_
    <div class="all-scroll">all-scroll</div>_x000D_
    <div class="col-resize">col-resize</div>_x000D_
    <div class="row-resize">row-resize</div>_x000D_
    <div class="n-resize">n-resize</div>_x000D_
    <div class="s-resize">s-resize</div>_x000D_
    <div class="e-resize">e-resize</div>_x000D_
    <div class="w-resize">w-resize</div>_x000D_
    <div class="ns-resize">ns-resize</div>_x000D_
    <div class="ew-resize">ew-resize</div>_x000D_
    <div class="ne-resize">ne-resize</div>_x000D_
    <div class="nw-resize">nw-resize</div>_x000D_
    <div class="se-resize">se-resize</div>_x000D_
    <div class="sw-resize">sw-resize</div>_x000D_
    <div class="nesw-resize">nesw-resize</div>_x000D_
    <div class="nwse-resize">nwse-resize</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java: notify() vs. notifyAll() all over again

Take a look at the code posted by @xagyg.

Suppose two different threads are waiting for two different conditions:
The first thread is waiting for buf.size() != MAX_SIZE, and the second thread is waiting for buf.size() != 0.

Suppose at some point buf.size() is not equal to 0. JVM calls notify() instead of notifyAll(), and the first thread is notified (not the second one).

The first thread is woken up, checks for buf.size() which might return MAX_SIZE, and goes back to waiting. The second thread is not woken up, continues to wait and does not call get().

How to remove border from specific PrimeFaces p:panelGrid?

Just add those lines on your custom css mycss.css

table tbody .ui-widget-content {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 0 solid #FFFFFF;
    color: #333333;
}

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

How to remove special characters from a string?

As described here http://developer.android.com/reference/java/util/regex/Pattern.html

Patterns are compiled regular expressions. In many cases, convenience methods such as String.matches, String.replaceAll and String.split will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.

public class RegularExpressionTest {

public static void main(String[] args) {
    System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$#@!#$%^&*()("));
    System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}

 public static String getOnlyDigits(String s) {
    Pattern pattern = Pattern.compile("[^0-9]");
    Matcher matcher = pattern.matcher(s);
    String number = matcher.replaceAll("");
    return number;
 }
 public static String getOnlyStrings(String s) {
    Pattern pattern = Pattern.compile("[^a-z A-Z]");
    Matcher matcher = pattern.matcher(s);
    String number = matcher.replaceAll("");
    return number;
 }
}

Result

String is = one
Number is = 9196390097

Properties file in python (similar to Java Properties)

I did this using ConfigParser as follows. The code assumes that there is a file called config.prop in the same directory where BaseTest is placed:

config.prop

[CredentialSection]
app.name=MyAppName

BaseTest.py:

import unittest
import ConfigParser

class BaseTest(unittest.TestCase):
    def setUp(self):
        __SECTION = 'CredentialSection'
        config = ConfigParser.ConfigParser()
        config.readfp(open('config.prop'))
        self.__app_name = config.get(__SECTION, 'app.name')

    def test1(self):
        print self.__app_name % This should print: MyAppName

Should __init__() call the parent class's __init__()?

In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:

object.__init__(self)

In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.

On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.

right align an image using CSS HTML

 img {
     display: block;
     margin-left: auto;
   }

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

git clone from another directory

It's as easy as it looks.

14:27:05 ~$ mkdir gittests
14:27:11 ~$ cd gittests/
14:27:13 ~/gittests$ mkdir localrepo
14:27:20 ~/gittests$ cd localrepo/
14:27:21 ~/gittests/localrepo$ git init
Initialized empty Git repository in /home/andwed/gittests/localrepo/.git/
14:27:22 ~/gittests/localrepo (master #)$ cd ..
14:27:35 ~/gittests$ git clone localrepo copyoflocalrepo
Cloning into 'copyoflocalrepo'...
warning: You appear to have cloned an empty repository.
done.
14:27:42 ~/gittests$ cd copyoflocalrepo/
14:27:46 ~/gittests/copyoflocalrepo (master #)$ git status
On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)
14:27:46 ~/gittests/copyoflocalrepo (master #)$ 

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Is it possible to run one logrotate check manually?

Issue the following command,the way to run specified logrotate:

logrotate -vf /etc/logrotate.d/custom

Options:

-v :show the process

-f :forcing run

custom :user-defined log setting

eg: mongodb-log

# mongodb-log rotate

/data/var/log/mongodb/mongod.log {
    daily
    dateext
    rotate 30
    copytruncate
    missingok
}

Splitting a Java String by the pipe symbol using split("|")

Use this code:

public static void main(String[] args) {
    String test = "A|B|C||D";

    String[] result = test.split("\\|");

    for (String s : result) {
        System.out.println(">" + s + "<");
    }
}

ASP.NET MVC Ajax Error handling

I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.

I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:

    [HttpPut]
    public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave) 
    {
        if (!ModelState.IsValid)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = "Model is not valid", Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
        try
        {
            MyDbContext db = new MyDbContext();

            db.Entry(employeToSave).State = EntityState.Modified;
            db.SaveChanges();

            DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];

            if (employeToSave.Id == user.Id)
            {
                user.Company = employeToSave.Company;
                user.Language = employeToSave.Language;
                user.Money = employeToSave.Money;
                user.CostCenter = employeToSave.CostCenter;

                Session["EmployeLoggin"] = user;
            }
        }
        catch (Exception ex) 
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = ex.Message, Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }

        return new JsonResult() { Data = new { Success = true }, };
    }

Later in the ajax call I just asked for this property to know if I had an exception:

$.ajax({
    url: 'UpdateEmployeeConfig',
    type: 'PUT',
    data: JSON.stringify(EmployeConfig),
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        if (data.Success) {
            //This is for the example. Please do something prettier for the user, :)
            alert('All was really ok');                                           
        }
        else {
            alert('Oups.. we had errors: ' + data.ErrorMessage);
        }
    },
    error: function (request, status, error) {
       alert('oh, errors here. The call to the server is not working.')
    }
});

Hope this helps. Happy code! :P

How to schedule a function to run every hour on Flask?

I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

Removing items from a ListBox in VB.net

I think your ListBox already clear with ListBox2.Items.Clear(). The problem is that you also need to clear your dataset from previous results with ds6.Tables.Clear().

Add this in your code:

da6 = New SqlDataAdapter("select distinct(component_type) from component where   component_name='" & ListBox1.SelectedItem() & "'", con)
    ListBox1.Items.Clear()    ' clears ListBox1
    ListBox2.Items.Clear()    ' clears ListBox2
    ds6.Tables.Clear()        ' clears DataSet  <======= DON'T FORGET TO DO THIS
da6.Fill(ds6, "component")
For Each row As DataRow In ds6.Tables(0).Rows
    ListBox2.Items.Add(row.Field(Of String)("component_type"))
Next

How to style a disabled checkbox?

If you're trying to stop someone from updating the checkbox so it appears disabled then just use JQuery

$('input[type=checkbox]').click(false);

You can then style the checkbox.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

IEnumerable<string> e = (from char c in source
                        select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
                        select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());

Then you can call ToList():

List<string> l = (from char c in source
                  select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
                  select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();

Undefined symbols for architecture x86_64 on Xcode 6.1

I just had this error when I opened a (quite) old project, created in Xcode 4~ish, in Xcode 6.4. While the linked Frameworks were visible in the Project sidebar, I overlooked that there were no linked libraries in the Target Build Phases tab. Once I fixed that, it compiled fine.

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

Why XML-Serializable class need a parameterless constructor

This is a limitation of XmlSerializer. Note that BinaryFormatter and DataContractSerializer do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.

Since you are using xml, you might consider using DataContractSerializer and marking your class with [DataContract]/[DataMember], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute] - everything becomes elements).

Update: if you really want to know, BinaryFormatter et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

I have my own serialization engine, but I don't intend making it use FormatterServices; I quite like knowing that a constructor (any constructor) has actually executed.

How to download file in swift?

Try This Code only Swift 3.0 First Create NS Object File Copy this code in created File

import UIKit

class Downloader : NSObject, URLSessionDownloadDelegate {

    var url : URL?
    // will be used to do whatever is needed once download is complete
    var obj1 : NSObject?

    init(_ obj1 : NSObject)
    {
        self.obj1 = obj1
    }

    //is called once the download is complete
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
    {
        //copy downloaded data to your documents directory with same names as source file
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        let destinationUrl = documentsUrl!.appendingPathComponent(url!.lastPathComponent)
        let dataFromURL = NSData(contentsOf: location)
        dataFromURL?.write(to: destinationUrl, atomically: true)

        //now it is time to do what is needed to be done after the download
        //obj1!.callWhatIsNeeded()
    }

    //this is to track progress
    private func URLSession(session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    {
    }

    // if there is an error during download this will be called
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    {
        if(error != nil)
        {
            //handle the error
            print("Download completed with error: \(error!.localizedDescription)");
        }
    }

    //method to be called to download
    func download(url: URL)
    {
        self.url = url

        //download identifier can be customized. I used the "ulr.absoluteString"
        let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
        let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
        let task = session.downloadTask(with: url)
        task.resume()
    }}

then Copy Below Code And put code in place of you want to download file

 object = "http://www.mywebsite.com/myfile.pdf"
       let url1 = URL(string: object!)
        Downloader(url1! as NSObject).download(url: url1!)

How to open a web page automatically in full screen mode

view full size page large (function () { var viewFullScreen = document.getElementById("view-fullscreen"); if (viewFullScreen) { viewFullScreen.addEventListener("click", function () { var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }, false); } })();

_x000D_
_x000D_
<div class="container">      _x000D_
            <section class="main-content">_x000D_
                                    <center><a href="#"><button id="view-fullscreen">view full size page large</button></a><center>_x000D_
                                           <script>(function () {_x000D_
    var viewFullScreen = document.getElementById("view-fullscreen");_x000D_
    if (viewFullScreen) {_x000D_
        viewFullScreen.addEventListener("click", function () {_x000D_
            var docElm = document.documentElement;_x000D_
            if (docElm.requestFullscreen) {_x000D_
                docElm.requestFullscreen();_x000D_
            }_x000D_
            else if (docElm.mozRequestFullScreen) {_x000D_
                docElm.mozRequestFullScreen();_x000D_
            }_x000D_
            else if (docElm.webkitRequestFullScreen) {_x000D_
                docElm.webkitRequestFullScreen();_x000D_
            }_x000D_
        }, false);_x000D_
    }_x000D_
    })();</script>_x000D_
                                           </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

for view demo clcik here demo of click to open page in fullscreen

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.

You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

Is there a Visual Basic 6 decompiler?

http://www.program-transformation.org/Transform/VisualBasicDecompilers

This link provides a lot of resources for VB6 Decompiling, but it seems like it will depend greatly on what you DO have (do you still have the pre-link Object code [EDIT: er... p-code I mean], or just the EXE?) Either way, it looks like there's something, take a look in there.

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

How can I format a decimal to always show 2 decimal places?

.format is a more readable way to handle variable formatting:

'{:.{prec}f}'.format(26.034, prec=2)

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery():

  1. will work with Action Queries only (Create,Alter,Drop,Insert,Update,Delete).
  2. Returns the count of rows effected by the Query.
  3. Return type is int
  4. Return value is optional and can be assigned to an integer variable.

ExecuteReader():

  1. will work with Action and Non-Action Queries (Select)
  2. Returns the collection of rows selected by the Query.
  3. Return type is DataReader.
  4. Return value is compulsory and should be assigned to an another object DataReader.

ExecuteScalar():

  1. will work with Non-Action Queries that contain aggregate functions.
  2. Return the first row and first column value of the query result.
  3. Return type is object.
  4. Return value is compulsory and should be assigned to a variable of required type.

Reference URL:

http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

I don't know why but i just renamed my source file COLARR.C to colarr.c and the error vanished! probably you need this

sudo apt-get install g++

How can I align text in columns using Console.WriteLine?

I really like those libraries mentioned here but I had an idea that could be simpler than just padding or doing tons of string manipulations,

You could just manually set your cursor using the maximum string length of your data. Here's some code to get the idea (not tested):

var column1[] = {"test", "longer test", "etc"}
var column2[] = {"data", "more data", "etc"}
var offset = strings.OrderByDescending(s => s.Length).First().Length;
for (var i = 0; i < column.Length; i++) {
    Console.Write(column[i]);
    Console.CursorLeft = offset + 1;
    Console.WriteLine(column2[i]);
}

you could easily extrapolate if you have more rows.

How can I disable a tab inside a TabControl?

You can simply use:

tabPage.Enabled = false;

This property is not shown, but it works without any problems.

You can program the Selecting event on TabControler to make it impossible to change to a non-editable tab:

private void tabControler_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPageIndex < 0) return;
    e.Cancel = !e.TabPage.Enabled;
}

How can I tell jackson to ignore a property for which I don't have control over the source code?

Mix-in annotations work pretty well here as already mentioned. Another possibility beyond per-property @JsonIgnore is to use @JsonIgnoreType if you have a type that should never be included (i.e. if all instances of GeometryCollection properties should be ignored). You can then either add it directly (if you control the type), or using mix-in, like:

@JsonIgnoreType abstract class MixIn { }
// and then register mix-in, either via SerializationConfig, or by using SimpleModule

This can be more convenient if you have lots of classes that all have a single 'IgnoredType getContext()' accessor or so (which is the case for many frameworks)

android layout with visibility GONE

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try this piece of code..For me this code worked..

Stylesheet not loaded because of MIME-type

Yet another reason for this error may be that the CSS file permissions are incorrect. In my case the file was inaccessible because ownership had been changed to the root user-- which happened due to pushing Git files as the root user.

PHP Sort a multidimensional array by element containing date

Use usort() and a custom comparison function:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($array, 'date_compare');

EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.

usort will pass two of these records to the given comparison function date_compare() at a a time. date_compare then extracts the "datetime" field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0 if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort() uses this information to sort the array.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

For me the solution was besides using "Ntlm" as credential type, similar as Jeroen K's solution. If I had the permission level I would plus on his post, but let me post my whole code here, which will support both Windows and other credential types like basic auth:

    XxxSoapClient xxxClient = new XxxSoapClient();
    ApplyCredentials(userName, password, xxxClient.ClientCredentials);

    private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
    {
        clientCredentials.UserName.UserName = userName;
        clientCredentials.UserName.Password = password;
        clientCredentials.Windows.ClientCredential.UserName = userName;
        clientCredentials.Windows.ClientCredential.Password = password;
        clientCredentials.Windows.AllowNtlm = true;
        clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    }  

How do I convert a String object into a Hash object?

I prefer to abuse ActiveSupport::JSON. Their approach is to convert the hash to yaml and then load it. Unfortunately the conversion to yaml isn't simple and you'd probably want to borrow it from AS if you don't have AS in your project already.

We also have to convert any symbols into regular string-keys as symbols aren't appropriate in JSON.

However, its unable to handle hashes that have a date string in them (our date strings end up not being surrounded by strings, which is where the big issue comes in):

string = '{'last_request_at' : 2011-12-28 23:00:00 UTC }' ActiveSupport::JSON.decode(string.gsub(/:([a-zA-z])/,'\\1').gsub('=>', ' : '))

Would result in an invalid JSON string error when it tries to parse the date value.

Would love any suggestions on how to handle this case

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Datanode process not running in Hadoop

I have got details of the issue in the log file like below : "Invalid directory in dfs.data.dir: Incorrect permission for /home/hdfs/dnman1, expected: rwxr-xr-x, while actual: rwxrwxr-x" and from there I identified that the datanote file permission was 777 for my folder. I corrected to 755 and it started working.

Printing prime numbers from 1 through 100

If j is equal to sqrt(i) it might also be a valid factor, not only if it's smaller.

To iterate up to and including sqrt(i) in your inner loop, you could write:

for (int j=2; j*j<=i; j++)

(Compared to using sqrt(i) this has the advantage to not need conversion to floating point numbers.)

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Try this It'll work perfect.

$('body.overflow-hidden').delegate('#skrollr-body','touchmove',function(e){
    e.preventDefault();
    console.log('Stop skrollrbody');
}).delegate('.mfp-auto-cursor .mfp-content','touchmove',function(e){
    e.stopPropagation();
    console.log('Scroll scroll');
});

Visual Studio keyboard shortcut to display IntelliSense

Additionally, Ctrl + K, Ctrl + I shows you Quick info (handy inside parameters)

Ctrl+Shift+Space shows you parameter information.

Switching between GCC and Clang/LLVM using CMake

According to the help of cmake:

-C <initial-cache>
     Pre-load a script to populate the cache.

     When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project.  This option may be used to specify a  file  from
     which to load cache entries before the first pass through the project's cmake listfiles.  The loaded entries take priority over the project's default values.  The given file should be a CMake
     script containing SET commands that use the CACHE option, not a cache-format file.

You make be able to create files like gcc_compiler.txt and clang_compiler.txt to includes all relative configuration in CMake syntax.

Clang Example (clang_compiler.txt):

 set(CMAKE_C_COMPILER "/usr/bin/clang" CACHE string "clang compiler" FORCE)

Then run it as

GCC:

cmake -C gcc_compiler.txt XXXXXXXX

Clang:

cmake -C clang_compiler.txt XXXXXXXX

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Depending on how your layout works, you might get away with setting the background on the <html> element, which is always at least the height of the viewport.

Get installed applications in a system

Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.

There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.

ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

Blur or dim background when Android PopupWindow active

Since PopupWindow just adds a View to WindowManager you can use updateViewLayout (View view, ViewGroup.LayoutParams params) to update the LayoutParams of your PopupWindow's contentView after calling show..().

Setting the window flag FLAG_DIM_BEHIND will dimm everything behind the window. Use dimAmount to control the amount of dim (1.0 for completely opaque to 0.0 for no dim).

Keep in mind that if you set a background to your PopupWindow it will put your contentView into a container, which means you need to update it's parent.

With background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(background);
popup.showAsDropDown(anchor);

View container = (View) popup.getContentView().getParent();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);

Without background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(null);
popup.showAsDropDown(anchor);

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) contentView.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(contentView, p);

Marshmallow Update:

On M PopupWindow wraps the contentView inside a FrameLayout called mDecorView. If you dig into the PopupWindow source you will find something like createDecorView(View contentView).The main purpose of mDecorView is to handle event dispatch and content transitions, which are new to M. This means we need to add one more .getParent() to access the container.

With background that would require a change to something like:

View container = (View) popup.getContentView().getParent().getParent();

Better alternative for API 18+

A less hacky solution using ViewGroupOverlay:

1) Get a hold of the desired root layout

ViewGroup root = (ViewGroup) getWindow().getDecorView().getRootView();

2) Call applyDim(root, 0.5f); or clearDim()

public static void applyDim(@NonNull ViewGroup parent, float dimAmount){
    Drawable dim = new ColorDrawable(Color.BLACK);
    dim.setBounds(0, 0, parent.getWidth(), parent.getHeight());
    dim.setAlpha((int) (255 * dimAmount));

    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.add(dim);
}

public static void clearDim(@NonNull ViewGroup parent) {
    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.clear();
}

How to get css background color on <tr> tag to span entire row

tr.rowhighlight td, tr.rowhighlight th{
    background-color:#f0f8ff;
}

How to enable directory listing in apache web server

See if you are able to access/list the '/icons/' directory. This is useful to test the behavior of Directory in Apache.

for eg : You might be having below config by default in your httpd.conf file.So hit the url : IP:Port/icons/ and see if it list the icons or not.You can also try by putting the 'directory/folder' inside the 'var/www/icons'.

Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>

If it does works then you can crosscheck or modify your custom directory configuration with '' configuration.

How to flush output of print function?

How to flush output of Python print?

I suggest five ways of doing this:

  • In Python 3, call print(..., flush=True) (the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).
  • Call file.flush() on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
  • apply this to every print function call in the module with a partial function,
    print = partial(print, flush=True) applied to the module global.
  • apply this to the process with a flag (-u) passed to the interpreter command
  • apply this to every python process in your environment with PYTHONUNBUFFERED=TRUE (and unset the variable to undo this).

Python 3.3+

Using Python 3.3 or higher, you can just provide flush=True as a keyword argument to the print function:

print('foo', flush=True) 

Python 2 (or < 3.3)

They did not backport the flush argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__ import must be at/very "near the top of your module"):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

The above compatibility code will cover most uses, but for a much more thorough treatment, see the six module.

Alternatively, you can just call file.flush() after printing, for example, with the print statement in Python 2:

import sys
print 'delayed output'
sys.stdout.flush()

Changing the default in one module to flush=True

You can change the default for the print function by using functools.partial on the global scope of a module:

import functools
print = functools.partial(print, flush=True)

if you look at our new partial function, at least in Python 3:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

We can see it works just like normal:

>>> print('foo')
foo

And we can actually override the new default:

>>> print('foo', flush=False)
foo

Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print function (or unreference the compatibility function, if using one in Python 2, in that current global scope).

If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.

Changing the default for the process

I think the best option here is to use the -u flag to get unbuffered output.

$ python -u script.py

or

$ python -um package.module

From the docs:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

Changing the default for the shell operating environment

You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:

e.g., in Linux or OSX:

$ export PYTHONUNBUFFERED=TRUE

or Windows:

C:\SET PYTHONUNBUFFERED=TRUE

from the docs:

PYTHONUNBUFFERED

If this is set to a non-empty string it is equivalent to specifying the -u option.


Addendum

Here's the help on the print function from Python 2.7.12 - note that there is no flush argument:

>>> from __future__ import print_function
>>> help(print)
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

How do I create a folder in VB if it doesn't exist?

Just do this:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.

Hope it helps!

-nfell2009

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have different modules installed and need to use a specific python install, then shebang appears to be limited at first. However, you can do tricks like the below to allow the shebang to be invoked first as a shell script and then choose python. This is very flexible imo:

#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3

if [ -x $PREFERRED_PYTHON ]; then
    echo Using preferred python $PREFERRED_PYTHON
    exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
    echo Using alternative python $ALTERNATIVE_PYTHON
    exec $ALTERNATIVE_PYTHON "$0" "$@"
else
    echo Using fallback python $FALLBACK_PYTHON
    exec python3 "$0" "$@"
fi
exit 127
'''

__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())

Or better yet, perhaps, to facilitate code reuse across multiple python scripts:

#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''

and then select.sh has:

PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3

if [ -x $PREFERRED_PYTHON ]; then
    CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
    CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
    CHOSEN_PYTHON=$FALLBACK_PYTHON
fi

How to output a comma delimited list in jinja python template?

you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

How to do the equivalent of pass by reference for primitives in Java

Make a

class PassMeByRef { public int theValue; }

then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.

How to connect to SQL Server database from JavaScript in the browser?

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

Push JSON Objects to array in localStorage

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How to append a newline to StringBuilder

you can use line.seperator for appending new line in

Enable remote connections for SQL Server Express 2012

One more thing to check is that you have spelled the named instance correctly!

This article is very helpful in troubleshooting connection problems: How to Troubleshoot Connecting to the SQL Server Database Engine

How to check file MIME type with javascript before upload?

Short answer is no.

As you note the browsers derive type from the file extension. Mac preview also seems to run off the extension. I'm assuming its because its faster reading the file name contained in the pointer, rather than looking up and reading the file on disk.

I made a copy of a jpg renamed with png.

I was able to consistently get the following from both images in chrome (should work in modern browsers).

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

Which you could hack out a String.indexOf('jpeg') check for image type.

Here is a fiddle to explore http://jsfiddle.net/bamboo/jkZ2v/1/

The ambigious line I forgot to comment in the example

console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

  • Splits the base64 encoded img data, leaving on the image
  • Base64 decodes the image
  • Matches only the first line of the image data

The fiddle code uses base64 decode which wont work in IE9, I did find a nice example using VB script that works in IE http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html

The code to load the image was taken from Joel Vardy, who is doing some cool image canvas resizing client side before uploading which may be of interest https://joelvardy.com/writing/javascript-image-upload

Which is faster: multiple single INSERTs or one multiple-row INSERT?

A major factor will be whether you're using a transactional engine and whether you have autocommit on.

Autocommit is on by default and you probably want to leave it on; therefore, each insert that you do does its own transaction. This means that if you do one insert per row, you're going to be committing a transaction for each row.

Assuming a single thread, that means that the server needs to sync some data to disc for EVERY ROW. It needs to wait for the data to reach a persistent storage location (hopefully the battery-backed ram in your RAID controller). This is inherently rather slow and will probably become the limiting factor in these cases.

I'm of course assuming that you're using a transactional engine (usually innodb) AND that you haven't tweaked the settings to reduce durability.

I'm also assuming that you're using a single thread to do these inserts. Using multiple threads muddies things a bit because some versions of MySQL have working group-commit in innodb - this means that multiple threads doing their own commits can share a single write to the transaction log, which is good because it means fewer syncs to persistent storage.

On the other hand, the upshot is, that you REALLY WANT TO USE multi-row inserts.

There is a limit over which it gets counter-productive, but in most cases it's at least 10,000 rows. So if you batch them up to 1,000 rows, you're probably safe.

If you're using MyISAM, there's a whole other load of things, but I'll not bore you with those. Peace.

What is the use of the JavaScript 'bind' method?

In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

Detecting iOS / Android Operating system

You also can create Firbase Dynamic links which will work as per your requirement. It supports multiple platforms. This link can be created, manually as well as via programming. You can then embed this link in QR code.

If the target app is installed, the link will redirect user to app. If its not installed it will redirect to Play Store/App store/Any other configured website.

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

How to debug when Kubernetes nodes are in 'Not Ready' state

I recently started using VMWare Octant https://github.com/vmware-tanzu/octant. This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).

Undo git stash pop that results in merge conflict

git checkout -f

must work, if your previous state is clean.

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I am getting the same error Due to following reason.

I have entered right credentials but with copy-paste. So that may b issue of junk characters insertion while copy paste. I have entered manually and ran the code and now its working fine

Thank You

Limit the size of a file upload (html input element)

This is completely possible. Use Javascript.

I use jQuery to select the input element. I have it set up with an on change event.

$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) { 

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
    $("#approvedFiles").val(approvedHTML);

});

The code above saves all the file names that I deem worthy of persisting to the submission page, before the submit actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server side we do have to filter these out. I haven't written any code for that yet, but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and match them to the $_FILES(PHP Superglobal, sorry I dont know ruby file variable) variable.

My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large wont be saved. This should work on all browsers because I'm not using FormData object.

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public ActionResult Index()
{
    byte[] contents = FetchPdfBytes();
    return File(contents, "application/pdf", "test.pdf");
}

and for opening the PDF inside the browser you will need to set the Content-Disposition header:

public ActionResult Index()
{
    byte[] contents = FetchPdfBytes();
    Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
    return File(contents, "application/pdf");
}

Where to find Application Loader app in Mac?

For anyone finding this now (23/09/2019) Application Loader has been removed from Xcode.

If you have built the application in Xcode you should be able to follow these instructions to upload your and distribute your project Upload an app

I am not sure what to do if you have been given a .ipa file, for example when building an Expo project, I'll update this post when i have an answer.

In the mean time more info can be found here. Developer Apple - Whats new

How to calculate a mod b in Python?

Why don't you use % ?


print 4 % 2 # 0

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

MS Excel showing the formula in a cell instead of the resulting value

If you are using VBA to enter formulas, it is possible to accidentally enter them incompletely:

Sub AlmostAFormula()
    With Range("A1")
        .Clear
        .NumberFormat = "@"
        .Value = "=B1+C1"
        .NumberFormat = "General"
    End With
End Sub

A1 will appear to have a formula, but it is only text until you double-click the cell and touch Enter .

Make sure you have no bugs like this in your code.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

You are getting this is because you are using a Anaconda distribution of Jupyter notebook. So just do conda install pandas restart your jupyter notebook and rerun your cell. It should work. If you are trying this on a Virtual Env try this

  1. conda create -n name_of_my_env python This will create a minimal environment with only Python installed in it. To put your self inside this environment run:

2 source activate name_of_my_env On Windows the command is: activate name_of_my_env The final step required is to install pandas. This can be done with the following command:

conda install pandas To install a specific pandas version:

conda install pandas=0.20.3

To install other packages, IPython for example:

conda install ipython To install the full Anaconda distribution:

conda install anaconda

If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:

conda install pip pip install django Installing from PyPI pandas can be installed via pip from PyPI.

pip install pandas Installing with ActivePython

Hope this helps.

Using variables inside strings

This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.

The recommended way to do this would be with String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);

However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

Hope you like it!

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Generating a random & unique 8 character string using MySQL

DELIMITER $$

USE `temp` $$

DROP PROCEDURE IF EXISTS `GenerateUniqueValue`$$

CREATE PROCEDURE `GenerateUniqueValue`(IN tableName VARCHAR(255),IN columnName VARCHAR(255)) 
BEGIN
    DECLARE uniqueValue VARCHAR(8) DEFAULT "";
    WHILE LENGTH(uniqueValue) = 0 DO
        SELECT CONCAT(SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
                SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1)
                ) INTO @newUniqueValue;
        SET @rcount = -1;
        SET @query=CONCAT('SELECT COUNT(*) INTO @rcount FROM  ',tableName,' WHERE ',columnName,'  like ''',@newUniqueValue,'''');
        PREPARE stmt FROM  @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    IF @rcount = 0 THEN
            SET uniqueValue = @newUniqueValue ;
        END IF ;
    END WHILE ;
    SELECT uniqueValue;
    END$$

DELIMITER ;

Use this stored procedure and use it everytime like

Call GenerateUniqueValue('tableName','columnName')

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

Changing text color of menu item in navigation drawer

To change the individual text color of a single item, use a SpannableString like below:

NavigationView navDrawer;
Menu menu = navDrawer.getMenu();

SpannableString spannableString = new SpannableString("Menu item"));
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), 0, spannableString.length(), 0);

menu.findItem(R.id.nav_item).setTitle(spannableString);

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

How to use NULL or empty string in SQL

In sproc, you can use the following condition:

DECLARE @USER_ID VARCAHR(15)=NULL --THIS VALUE IS NULL OR EMPTY DON'T MATTER
IF(COALESCE(@USER_ID,'')='')
PRINT 'HUSSAM'

Loading resources using getClass().getResource()

As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".

For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".

FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("../app1.fxml"));

Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.

How to change the default GCC compiler in Ubuntu?

Now, there is gcc-4.9 available for Ubuntu/precise.

Create a group of compiler alternatives where the distro compiler has a higher priority:

root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.

List available compiler alternatives:

root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin

To select manually version 4.9 of gcc, g++ and cpp, do:

root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin

Check compiler versions:

root$ for i in gcc g++ cpp ; do $i --version ; done

Restore distro compiler settings (here: back to v4.6):

root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin

How to subtract days from a plain Date?

_x000D_
_x000D_
var d = new Date();_x000D_
_x000D_
document.write('Today is: ' + d.toLocaleString());_x000D_
_x000D_
d.setDate(d.getDate() - 31);_x000D_
_x000D_
document.write('<br>5 days ago was: ' + d.toLocaleString());
_x000D_
_x000D_
_x000D_

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

Function that creates a timestamp in c#

when you need in a timestamp in seconds, you can use the following:

var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;

How can I create and style a div using JavaScript?

This will be inside a function or script tag with custom CSS with classname as Custom

 var board = document.createElement('div');
 board.className = "Custom";
 board.innerHTML = "your data";
 console.log(count);
 document.getElementById('notification').appendChild(board);

How to find all the dependencies of a table in sql server

Method 1: Using sp_depends

 sp_depends 'dbo.First'
 GO

Method 2 : Using sys.procedures for Stored Procedures

select Name from sys.procedures where OBJECT_DEFINITION(OBJECT_ID) like '%Any Keyword Name%'

'% Any Keyword Name %' is the Search keyword you are looking for

Method 3 : Using sys.views for Views

select Name from sys.views where OBJECT_DEFINITION(OBJECT_ID) like '%Any Keyword Name%'

'% Any Keyword Name %' is the Search keyword you are looking for

Get escaped URL parameter

Need to add the i parameter to make it case insensitive:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }

Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.