Programs & Examples On #Doctrine inheritance

How do I convert NSMutableArray to NSArray?

In objective-c :

NSArray *myArray = [myMutableArray copy];

In swift :

 var arr = myMutableArray as NSArray

How to initialize an array in Kotlin with values?

In Kotlin There are Several Ways.

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

var arr = IntArray(size){0}  // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index

We also can create array with built in function like-

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Another way

var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

Listing information about all database files in SQL Server

This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.

IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
 DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
 (
    Drive CHAR(1)
    ,MBFree INT
 ) 

INSERT  INTO #DriveInfo
      EXEC master..xp_fixeddrives


IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL 
   DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
      [ServerName] [nvarchar](128) NULL
      ,[DBName] [nvarchar](128)  NULL
      ,[database_id] [int] NULL
      ,[create_date] datetime NULL
      ,[CompatibilityLevel] [int] NULL
      ,[collation_name] [nvarchar](128) NULL
      ,[state_desc] [nvarchar](60) NULL
      ,[recovery_model_desc] [nvarchar](60) NULL
      ,[DataFileLocations] [nvarchar](4000)
      ,[DataFilesMB] money null
      ,DataVolumeFreeSpaceMB INT NULL
      ,[LogFileLocations] [nvarchar](4000)
      ,[LogFilesMB] money null
      ,LogVolumeFreeSpaceMB INT NULL

) ON [PRIMARY]

INSERT INTO [dbo].[Tmp_tblDatabaseInfo] 
SELECT 
      @@SERVERNAME AS [ServerName] 
      ,d.name AS DBName 
      ,d.database_id
      ,d.create_date
      ,d.compatibility_level  
      ,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
      ,d.[state_desc]
      ,d.recovery_model_desc
      ,(select physical_name + ' | ' AS [text()]
         from sys.master_files m
         WHERE m.type = 0 and m.database_id = d.database_id
         ORDER BY file_id
         FOR XML PATH ('')) AS DataFileLocations
      ,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id)  AS DataFilesMB
      ,NULL
      ,(select physical_name + ' | ' AS [text()]
         from sys.master_files m
         WHERE m.type = 1 and m.database_id = d.database_id
         ORDER BY file_id
         FOR XML PATH ('')) AS LogFileLocations
      ,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id)  AS LogFilesMB
      ,NULL
FROM  sys.databases d  

WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo] 
   SET DataFileLocations = 
      CASE WHEN LEN(DataFileLocations) > 4 THEN  LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
   ,LogFileLocations =
      CASE WHEN LEN(LogFileLocations) > 4 THEN  LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
   ,DataFilesMB = 
      CASE WHEN DataFilesMB > 0 THEN  DataFilesMB * 8 / 1024.0   ELSE NULL END
   ,LogFilesMB = 
      CASE WHEN LogFilesMB > 0 THEN  LogFilesMB * 8 / 1024.0  ELSE NULL END
   ,DataVolumeFreeSpaceMB = 
      (SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
   ,LogVolumeFreeSpaceMB = 
      (SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))

select * from [dbo].[Tmp_tblDatabaseInfo] 

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Forcing to download a file using PHP

Or you can do this using HTML5. Simply with

<a href="example.csv" download>download not open it</a>

How to specify the private SSH-key to use when executing shell command on Git?

In Windows with Git Bash you can use the following to add a repository

ssh-agent bash -c 'ssh-add "key-address"; git remote add origin "rep-address"'

for example:

ssh-agent bash -c 'ssh-add /d/test/PrivateKey.ppk; git remote add origin [email protected]:test/test.git'

Which private key is in drive D, folder test of computer. Also if you want to clone a repository, you can change git remote add origin with git clone.

After enter this to Git Bash, it will ask you for passphrase!

Be Aware that openssh private key and putty private key are different!

If you have created your keys with puttygen, you must convert your private key to openssh!

How can I read the client's machine/computer name from the browser?

No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.

Incomplete type is not allowed: stringstream

An incomplete type error is when the compiler encounters the use of an identifier that it knows is a type, for instance because it has seen a forward-declaration of it (e.g. class stringstream;), but it hasn't seen a full definition for it (class stringstream { ... };).

This could happen for a type that you haven't used in your own code but is only present through included header files -- when you've included header files that use the type, but not the header file where the type is defined. It's unusual for a header to not itself include all the headers it needs, but not impossible.

For things from the standard library, such as the stringstream class, use the language standard or other reference documentation for the class or the individual functions (e.g. Unix man pages, MSDN library, etc.) to figure out what you need to #include to use it and what namespace to find it in if any. You may need to search for pages where the class name appears (e.g. man -k stringstream).

Collectors.toMap() keyMapper -- more succinct expression?

You can use a lambda:

Collectors.toMap(p -> p.getLast(), Function.identity())

or, more concisely, you can use a method reference using :::

Collectors.toMap(Person::getLast, Function.identity())

and instead of Function.identity, you can simply use the equivalent lambda:

Collectors.toMap(Person::getLast, p -> p)

If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

Sadly, they want us to use a tag to let their browser know what to do. Look at this documentation, it tell us to use:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

and it should do.

SQL Server query to find all permissions/access for all users in a database

Due to low rep can't reply with this to the people asking to run this on multiple databases/SQL Servers.

Create a registered server group and query across them all us the following and just cursor through the databases:

--Make sure all ' are doubled within the SQL string.

DECLARE @dbname VARCHAR(50)   
DECLARE @statement NVARCHAR(max)

DECLARE db_cursor CURSOR 
LOCAL FAST_FORWARD
FOR  
SELECT name
FROM MASTER.dbo.sysdatabases
where name like '%DBName%'

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @dbname  
WHILE @@FETCH_STATUS = 0  
BEGIN  

SELECT @statement = 'use '+@dbname +';'+ '
/*
Security Audit Report
1) List all access provisioned to a SQL user or Windows user/group directly
2) List all access provisioned to a SQL user or Windows user/group through a database or application role
3) List all access provisioned to the public role

Columns Returned:
UserType        : Value will be either ''SQL User'', ''Windows User'', or ''Windows Group''.
                  This reflects the type of user/group defined for the SQL Server account.
DatabaseUserName: Name of the associated user as defined in the database user account.  The database user may not be the
                  same as the server user.
LoginName       : SQL or Windows/Active Directory user account.  This could also be an Active Directory group.
Role            : The role name.  This will be null if the associated permissions to the object are defined at directly
                  on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType  : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
                  DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ObjectType      : Type of object the user/role is assigned permissions on.  Examples could include USER_TABLE,
                  SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
Schema          : Name of the schema the object is in.
ObjectName      : Name of the object that the user/role is assigned permissions on.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ColumnName      : Name of the column of the object that the user/role is assigned permissions on. This value
                  is only populated if the object is a table, view or a table value function.
*/

    --1) List all access provisioned to a SQL user or Windows user/group directly
    SELECT
        [UserType] = CASE princ.[type]
                         WHEN ''S'' THEN ''SQL User''
                         WHEN ''U'' THEN ''Windows User''
                         WHEN ''G'' THEN ''Windows Group''
                     END,
        [DatabaseUserName] = princ.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = NULL,
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Database user
        sys.database_principals            AS princ
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = princ.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = princ.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        princ.[type] IN (''S'',''U'',''G'')
        -- No need for these system accounts
        AND princ.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')

UNION

    --2) List all access provisioned to a SQL user or Windows user/group through a database or application role
    SELECT
        [UserType] = CASE membprinc.[type]
                         WHEN ''S'' THEN ''SQL User''
                         WHEN ''U'' THEN ''Windows User''
                         WHEN ''G'' THEN ''Windows Group''
                     END,
        [DatabaseUserName] = membprinc.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Role/member associations
        sys.database_role_members          AS members
        --Roles
        JOIN      sys.database_principals  AS roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
        --Role members (database users)
        JOIN      sys.database_principals  AS membprinc ON membprinc.[principal_id] = members.[member_principal_id]
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = membprinc.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        membprinc.[type] IN (''S'',''U'',''G'')
        -- No need for these system accounts
        AND membprinc.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')

UNION

    --3) List all access provisioned to the public role, which everyone gets by default
    SELECT
        [UserType]         = ''{All Users}'',
        [DatabaseUserName] = ''{All Users}'',
        [LoginName]        = ''{All Users}'',
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Roles
        sys.database_principals            AS roleprinc
        --Role permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        --All objects
        JOIN      sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        roleprinc.[type] = ''R''
        AND roleprinc.[name] = ''public''
        AND obj.[is_ms_shipped] = 0

ORDER BY
    [UserType],
    [DatabaseUserName],
    [LoginName],
    [Role],
    [Schema],
    [ObjectName],
    [ColumnName],
    [PermissionType],
    [PermissionState],
    [ObjectType]
'
exec sp_executesql @statement

FETCH NEXT FROM db_cursor INTO @dbname  
END  
CLOSE db_cursor  
DEALLOCATE db_cursor 

This thread massively helped me thanks everyone!

jQuery - find table row containing table cell containing specific text

I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.

$("tr:contains(needle)"); //where needle is the text you are searching for.

For example, if you are searching for the text 'box', that would be:

$("tr:contains('box')");

This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements

HTML table sort

Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)

https://github.com/paulopmx/Flexigrid - Flexgrid
http://datatables.net/index - Data tables.
https://github.com/tonytomov/jqGrid

If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:

      Type |         Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
  TINYTEXT |           255 |           ±44 |              ±23
      TEXT |        65,535 |       ±11,000 |           ±5,900
MEDIUMTEXT |    16,777,215 |    ±2,800,000 |       ±1,500,000
  LONGTEXT | 4,294,967,295 |  ±740,000,000 |     ±380,000,000

In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.

Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.

CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).

This is of course ignoring storage overheads etc.

Fastest way to iterate over all the chars in a String

String.toCharArray() creates new char array, means allocation of memory of string length, then copies original char array of string using System.arraycopy() and then returns this copy to caller. String.charAt() returns character at position i from original copy, that's why String.charAt() will be faster than String.toCharArray(). Although, String.toCharArray() returns copy and not char from original String array, where String.charAt() returns character from original char array. Code below returns value at the specified index of this string.

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

code below returns a newly allocated character array whose length is the length of this string

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Common Header / Footer with static HTML

The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.

How do I remove a property from a JavaScript object?

Using delete method is the best way to do that, as per MDN description, the delete operator removes a property from an object. So you can simply write:

delete myObject.regex;
// OR
delete myObject['regex'];

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios:

  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true

  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).

  • Any property declared with var cannot be deleted from the global scope or from a function's scope.

  • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function (expression).

  • Functions which are part of an object (apart from the
    global scope) can be deleted with delete.

  • Any property declared with let or const cannot be deleted from the scope within which they were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().

The following snippet gives another simple example:

_x000D_
_x000D_
var Employee = {_x000D_
      age: 28,_x000D_
      name: 'Alireza',_x000D_
      designation: 'developer'_x000D_
    }_x000D_
    _x000D_
    console.log(delete Employee.name);   // returns true_x000D_
    console.log(delete Employee.age);    // returns true_x000D_
    _x000D_
    // When trying to delete a property that does _x000D_
    // not exist, true is returned _x000D_
    console.log(delete Employee.salary); // returns true
_x000D_
_x000D_
_x000D_

For more info about and seeing more example, visit the link below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

Difference between setTimeout with and without quotes and parentheses

    ##If i want to wait for some response from server or any action we use setTimeOut.

    functionOne =function(){
    console.info("First");

    setTimeout(()=>{
    console.info("After timeOut 1");
    },5000);
    console.info("only setTimeOut() inside code waiting..");
    }

    functionTwo =function(){
    console.info("second");
    }
    functionOne();
    functionTwo();

## So here console.info("After timeOut 1"); will be executed after time elapsed.
Output:
******************************************************************************* 
First
only setTimeOut() inside code waiting..
second
undefined
After timeOut 1  // executed after time elapsed.

sed whole word search and replace

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment

Equivalent to AssemblyInfo in dotnet core/csproj

Adding to NightOwl888's answer, you can go one step further and add an AssemblyInfo class rather than just a plain class:

enter image description here

How to match "anything up until this sequence of characters" in a regular expression?

On python:

.+?(?=abc) works for the single line case.

[^]+?(?=abc) does not work, since python doesn't recognize [^] as valid regex. To make multiline matching work, you'll need to use the re.DOTALL option, for example:

re.findall('.+?(?=abc)', data, re.DOTALL)

height: 100% for <div> inside <div> with display: table-cell

Make the the table-cell position relative, then make the inner div position absolute, with top/right/bottom/left all set to 0px.

.table-cell {
  display: table-cell;
  position: relative;
}

.inner-div {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
}

How to find list of possible words from a letter matrix [Boggle Solver]

A Node.JS JavaScript solution. Computes all 100 unique words in less than a second which includes reading dictionary file (MBA 2012).

Output:
["FAM","TUX","TUB","FAE","ELI","ELM","ELB","TWA","TWA","SAW","AMI","SWA","SWA","AME","SEA","SEW","AES","AWL","AWE","SEA","AWA","MIX","MIL","AST","ASE","MAX","MAE","MAW","MEW","AWE","MES","AWL","LIE","LIM","AWA","AES","BUT","BLO","WAS","WAE","WEA","LEI","LEO","LOB","LOX","WEM","OIL","OLM","WEA","WAE","WAX","WAF","MILO","EAST","WAME","TWAS","TWAE","EMIL","WEAM","OIME","AXIL","WEST","TWAE","LIMB","WASE","WAST","BLEO","STUB","BOIL","BOLE","LIME","SAWT","LIMA","MESA","MEWL","AXLE","FAME","ASEM","MILE","AMIL","SEAX","SEAM","SEMI","SWAM","AMBO","AMLI","AXILE","AMBLE","SWAMI","AWEST","AWEST","LIMAX","LIMES","LIMBU","LIMBO","EMBOX","SEMBLE","EMBOLE","WAMBLE","FAMBLE"]

Code:

var fs = require('fs')

var Node = function(value, row, col) {
    this.value = value
    this.row = row
    this.col = col
}

var Path = function() {
    this.nodes = []
}

Path.prototype.push = function(node) {
    this.nodes.push(node)
    return this
}

Path.prototype.contains = function(node) {
    for (var i = 0, ii = this.nodes.length; i < ii; i++) {
        if (this.nodes[i] === node) {
            return true
        }
    }

    return false
}

Path.prototype.clone = function() {
    var path = new Path()
    path.nodes = this.nodes.slice(0)
    return path
}

Path.prototype.to_word = function() {
    var word = ''

    for (var i = 0, ii = this.nodes.length; i < ii; ++i) {
        word += this.nodes[i].value
    }

    return word
}

var Board = function(nodes, dict) {
    // Expects n x m array.
    this.nodes = nodes
    this.words = []
    this.row_count = nodes.length
    this.col_count = nodes[0].length
    this.dict = dict
}

Board.from_raw = function(board, dict) {
    var ROW_COUNT = board.length
      , COL_COUNT = board[0].length

    var nodes = []

    // Replace board with Nodes
    for (var i = 0, ii = ROW_COUNT; i < ii; ++i) {
        nodes.push([])
        for (var j = 0, jj = COL_COUNT; j < jj; ++j) {
            nodes[i].push(new Node(board[i][j], i, j))
        }
    }

    return new Board(nodes, dict)
}

Board.prototype.toString = function() {
    return JSON.stringify(this.nodes)
}

Board.prototype.update_potential_words = function(dict) {
    for (var i = 0, ii = this.row_count; i < ii; ++i) {
        for (var j = 0, jj = this.col_count; j < jj; ++j) {
            var node = this.nodes[i][j]
              , path = new Path()

            path.push(node)

            this.dfs_search(path)
        }
    }
}

Board.prototype.on_board = function(row, col) {
    return 0 <= row && row < this.row_count && 0 <= col && col < this.col_count
}

Board.prototype.get_unsearched_neighbours = function(path) {
    var last_node = path.nodes[path.nodes.length - 1]

    var offsets = [
        [-1, -1], [-1,  0], [-1, +1]
      , [ 0, -1],           [ 0, +1]
      , [+1, -1], [+1,  0], [+1, +1]
    ]

    var neighbours = []

    for (var i = 0, ii = offsets.length; i < ii; ++i) {
        var offset = offsets[i]
        if (this.on_board(last_node.row + offset[0], last_node.col + offset[1])) {

            var potential_node = this.nodes[last_node.row + offset[0]][last_node.col + offset[1]]
            if (!path.contains(potential_node)) {
                // Create a new path if on board and we haven't visited this node yet.
                neighbours.push(potential_node)
            }
        }
    }

    return neighbours
}

Board.prototype.dfs_search = function(path) {
    var path_word = path.to_word()

    if (this.dict.contains_exact(path_word) && path_word.length >= 3) {
        this.words.push(path_word)
    }

    var neighbours = this.get_unsearched_neighbours(path)

    for (var i = 0, ii = neighbours.length; i < ii; ++i) {
        var neighbour = neighbours[i]
        var new_path = path.clone()
        new_path.push(neighbour)

        if (this.dict.contains_prefix(new_path.to_word())) {
            this.dfs_search(new_path)
        }
    }
}

var Dict = function() {
    this.dict_array = []

    var dict_data = fs.readFileSync('./web2', 'utf8')
    var dict_array = dict_data.split('\n')

    for (var i = 0, ii = dict_array.length; i < ii; ++i) {
        dict_array[i] = dict_array[i].toUpperCase()
    }

    this.dict_array = dict_array.sort()
}

Dict.prototype.contains_prefix = function(prefix) {
    // Binary search
    return this.search_prefix(prefix, 0, this.dict_array.length)
}

Dict.prototype.contains_exact = function(exact) {
    // Binary search
    return this.search_exact(exact, 0, this.dict_array.length)
}

Dict.prototype.search_prefix = function(prefix, start, end) {
    if (start >= end) {
        // If no more place to search, return no matter what.
        return this.dict_array[start].indexOf(prefix) > -1
    }

    var middle = Math.floor((start + end)/2)

    if (this.dict_array[middle].indexOf(prefix) > -1) {
        // If we prefix exists, return true.
        return true
    } else {
        // Recurse
        if (prefix <= this.dict_array[middle]) {
            return this.search_prefix(prefix, start, middle - 1)
        } else {
            return this.search_prefix(prefix, middle + 1, end)
        }
    }
}

Dict.prototype.search_exact = function(exact, start, end) {
    if (start >= end) {
        // If no more place to search, return no matter what.
        return this.dict_array[start] === exact
    }

    var middle = Math.floor((start + end)/2)

    if (this.dict_array[middle] === exact) {
        // If we prefix exists, return true.
        return true
    } else {
        // Recurse
        if (exact <= this.dict_array[middle]) {
            return this.search_exact(exact, start, middle - 1)
        } else {
            return this.search_exact(exact, middle + 1, end)
        }
    }
}

var board = [
    ['F', 'X', 'I', 'E']
  , ['A', 'M', 'L', 'O']
  , ['E', 'W', 'B', 'X']
  , ['A', 'S', 'T', 'U']
]

var dict = new Dict()

var b = Board.from_raw(board, dict)
b.update_potential_words()
console.log(JSON.stringify(b.words.sort(function(a, b) {
    return a.length - b.length
})))

What's the difference between jquery.js and jquery.min.js?

They are both the same functionally but the .min one has all unnecessary characters removed in order to make the file size smaller.

Just to point out as well, you are better using the minified version (.min) for your live environment as Google are now checking on page loading times. Having all your JS file minified means they will load faster and will score you more brownie points.

You can get an addon for Mozilla called Page Speed that will look through your site and show you all the .JS files and provide minified versions (amongst other things).

PHP Excel Header

Try this

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

How can I suppress all output from a command using Bash?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 )
$ echo $?
0
$ DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
0

Angular, content type is not being sent with $http

         $http({
                method: 'GET',
                url:'/http://localhost:8080/example/test' + toto,
                data: '',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(
                function(response) {
                    return response.data;
                }, 
                function(errResponse) {
                    console.error('Error !!');
                    return $q.reject(errResponse);
                }

How do I get bit-by-bit data from an integer value in C?

As requested, I decided to extend my comment on forefinger's answer to a full-fledged answer. Although his answer is correct, it is needlessly complex. Furthermore all current answers use signed ints to represent the values. This is dangerous, as right-shifting of negative values is implementation-defined (i.e. not portable) and left-shifting can lead to undefined behavior (see this question).

By right-shifting the desired bit into the least significant bit position, masking can be done with 1. No need to compute a new mask value for each bit.

(n >> k) & 1

As a complete program, computing (and subsequently printing) an array of single bit values:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    unsigned
        input = 0b0111u,
        n_bits = 4u,
        *bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
        bit = 0;

    for(bit = 0; bit < n_bits; ++bit)
        bits[bit] = (input >> bit) & 1;

    for(bit = n_bits; bit--;)
        printf("%u", bits[bit]);
    printf("\n");

    free(bits);
}

Assuming that you want to calculate all bits as in this case, and not a specific one, the loop can be further changed to

for(bit = 0; bit < n_bits; ++bit, input >>= 1)
    bits[bit] = input & 1;

This modifies input in place and thereby allows the use of a constant width, single-bit shift, which may be more efficient on some architectures.

Sass nth-child nesting

You're trying to do &(2), &(4) which won't work

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}
      }
  }
}

Git status shows files as changed even though contents are the same

I recently moved my local repo from one Windows x64 system to another. The first time I use it half my files appear to be changed. Thanks to Jacek Szybisz for sending me to Configuring Git to handle line endings where I found the following one-liner that removed all the no-change files from Gitkraken's change queue:

git config --global core.autocrlf true

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

iOS: set font size of UILabel Programmatically

This code is perfectly working for me.

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
  [label setFont:[UIFont systemFontOfSize:11]];

SQL how to make null values come last when sorting ascending

(A "bit" late, but this hasn't been mentioned at all)

You didn't specify your DBMS.

In standard SQL (and most modern DBMS like Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB and H2) you can specify NULLS LAST or NULLS FIRST:

Use NULLS LAST to sort them to the end:

select *
from some_table
order by some_column DESC NULLS LAST

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

How to delete node from XML file using C#

It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.

In your case you will find the four nodes that you want using this expression:

XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");

How to enter quotes in a Java string?

Here is full java example:-

public class QuoteInJava {     

public static void main (String args[])
    {
            System.out.println ("If you need to 'quote' in Java");
            System.out.println ("you can use single \' or double \" quote");
    }
}

Here is Out PUT:-

If you need to 'quote' in Java
you can use single ' or double " quote

enter image description here

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get images in Bootstrap's card to be the same height/width?

you can fix this problem with style like this.

<div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/butterPecan.jpg" style="width: 18rem; height: 20rem;" />

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

From the Intel Instructions

"The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to finish installation.

Extract the installer inside the "extras" directory and follow the installation instructions for your platform."

SQL - Select first 10 rows only?

What you're looking for is a LIMIT clause.

SELECT a.names,
         COUNT(b.post_title) AS num
    FROM wp_celebnames a
    JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0
    WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY a.names
ORDER BY num DESC
   LIMIT 10

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};

Convert string date to timestamp in Python

A simple function to get UNIX Epoch time.

NOTE: This function assumes the input date time is in UTC format (Refer to comments here).

def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
    import datetime, calendar
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

Usage:

>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600

Sending email from Azure

If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.

Disclaimer: I’m working at Mailjet as a Developer Evangelist.

Case-Insensitive List Search

I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:

using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

An App ID with Identifier '' is not available. Please enter a different string

This may only apply to the latest version of Xcode (7.3 D175), recently release:

Press the Try Again Button

After several hours of fiddling with Xcode build settings and starting the Certificate/App ID/Provisioning Profile dance from scratch, I ended up at the same place, same error message, App ID not available.

In frustration, I pressed the Try Again button thinking it was futile. But it worked.

In Java what is the syntax for commenting out multiple lines?

/* 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
*/

fatal: The current branch master has no upstream branch

For me, it was because I had deleted the hidden .git folder.

I fixed it by deleting the folder, re-cloning, and re-making the changes.

jQuery access input hidden value

Watch out if you want to retrieve a boolean value from a hidden field!

For example:

<input type="hidden" id="SomeBoolean" value="False"/>

(An input like this will be rendered by ASP MVC if you use @Html.HiddenFor(m => m.SomeBoolean).)

Then the following will return a string 'False', not a JS boolean!

var notABool = $('#SomeBoolean').val();

If you want to use the boolean for some logic, use the following instead:

var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }

Calculate Age in MySQL (InnoDb)

Try this:

SET @birthday = CAST('1980-05-01' AS DATE);
SET @today = CURRENT_DATE();

SELECT YEAR(@today) - YEAR(@birthday) - 
  (CASE WHEN
    MONTH(@birthday) > MONTH(@today) OR 
    (MONTH(@birthday) = MONTH(@today) AND DAY(@birthday) > DAY(@today)) 
      THEN 1 
      ELSE 0 
  END);

It returns this year - birth year (how old the person will be this year after the birthday) and adjusts based on whether the person has had the birthday yet this year.

It doesn't suffer from the rounding errors of other methods presented here.

Freely adapted from here

How do I make an HTML button not reload the page

You could add a click handler on the button with jQuery and do return false.

$("input[type='submit']").click(function() { return false; });

or

$("form").submit(function() { return false; });

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

parsing JSONP $http.jsonp() response in angular.js

You still need to set callback in the params:

var params = {
  'a': b,
  'token_auth': TOKEN,
  'callback': 'functionName'
};
$sce.trustAsResourceUrl(url);

$http.jsonp(url, {
  params: params
});

Where 'functionName' is a stringified reference to globally defined function. You can define it outside of your angular script and then redefine it in your module.

How can I add a line to a file in a shell script?

This doesn't use sed, but using >> will append to a file. For example:

echo 'one, two, three' >> testfile.csv

Edit: To prepend to a file, try something like this:

echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile

I found this through a quick Google search.

How do I install and use curl on Windows?

Thought I'd write exactly what I did (Windows 10, 64-bit):

From the download page https://curl.haxx.se/download.html choose the download wizard https://curl.haxx.se/dlwiz/

Choose curl executable.

Choose Win64.

Choose generic.

Choose any.

Choose x86_64.

Choose the first recommended option. For me this was:

curl version: 7.53.1 - SSL enabled SSH enabled. Provided by: Viktor Szakáts. This package is type curl executable You will get a pre-built 'curl' binary from this link (or in some cases, by using the information that is provided at the page this link takes you). You may or may not get 'libcurl' installed as a shared library/DLL. The file is packaged using 7zip. 7zip is a file archiving format.

Click download.

You should have the file curl-7.53.1-win64-mingw.7z in your downloads folder.

Install 7-Zip if you don't have it.

Right-click, 7-Zip, Extract Here. Copy and paste the extracted file somewhere like Z:\Tools\

If you look in the bin folder you'll see curl.exe. If you double-click it a window will quickly flash up and vanish. To run it you need to use the Command Prompt. Navigate to the bin folder and type curl followed by your parameters to make a request. You must use double-quotes. Single quotes won't work with curl on Windows.

Now you'll want to add curl to a user's Path variable so you don't have to navigate to the right folder to run the program. Go to This PC, Computer, System Properties, Advanced system settings, authenticate as an administrator (you're not running as admin, right? Right?) Environment Variables, System variables, look at the list and select Path, then Edit, then New, then, e.g.

Z:\Tools\curl-7.53.1-win64-mingw\bin

You can add a trailing backslash if you like, I don't think it matters. Click move up until it's at the top of the list, then you can see it easily from the previous screen. Click OK, OK, OK, then crack open a Command Prompt and you can run curl by typing curl from any folder, as any user. Don't forget your double-quotes.

This is the answer I wish I'd had.

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

How do I set a VB.Net ComboBox default value

Much simpler solution, Select the Combo-box, and in the option of Selected item, select the item index (0 for the first item) and set it to be the default value in the combo box.

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

In Bash you can do it by enabling the extglob option, like this (replace ls with cp and add the target directory, of course)

~/foobar> shopt extglob
extglob        off
~/foobar> ls
abar  afoo  bbar  bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob  # Enables extglob
~/foobar> ls !(b*)
abar  afoo
~/foobar> ls !(a*)
bbar  bfoo
~/foobar> ls !(*foo)
abar  bbar

You can later disable extglob with

shopt -u extglob

Delete file from internal storage

This is an old topic, but I will add my experience, maybe someone finds this helpful

>     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created

2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it

solution1:

              Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri

here I initialize Content resolver and delete it with a passed parameter of that URI

            ContentResolver contentResolver = getContentResolver ();
            contentResolver.delete (uriDelete,null ,null );

solution2(my first solution-from head in this time I do know that ): content resolver exists...

              String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                    adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);

            File file = new File (path);
            if (file != null) {
                file.delete ();
            }

Hope that this will be helpful to someone happy coding

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Hashing a file in Python

import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
    print(h2,file=e)


with open("encrypted.txt","r") as e:
    p = e.readline().strip()
    print(p)

How to 'update' or 'overwrite' a python list

If you are trying to take a value from the same array and trying to update it, you can use the following code.

{  'condition': { 
                     'ts': [   '5a81625ba0ff65023c729022',
                               '5a8161ada0ff65023c728f51',
                               '5a815fb4a0ff65023c728dcd']}

If the collection is userData['condition']['ts'] and we need to

    for i,supplier in enumerate(userData['condition']['ts']): 
        supplier = ObjectId(supplier)
        userData['condition']['ts'][i] = supplier

The output will be

{'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                            ObjectId('5a8161ada0ff65023c728f51'),
                            ObjectId('5a815fb4a0ff65023c728dcd')]}

How to create a new schema/new user in Oracle Database 11g?

It's a working example:

CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;

How to create a table from select query result in SQL Server 2008

Please be careful, MSSQL: "SELECT * INTO NewTable FROM OldTable"

is not always the same as MYSQL: "create table temp AS select.."

I think that there are occasions when this (in MSSQL) does not guarantee that all the fields in the new table are of the same type as the old.

For example :

create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable

does not always yield:

create table newTable (field1 varchar(10), field2 integer, field3 float)

but may be:

create table newTable (field1 varchar(10), field2 integer, field3 integer)

How to stop an animation (cancel() does not work)

To stop animation you may set such objectAnimator that do nothing, e.g.

first when manual flipping there is animation left to right:

flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);

then when switching to auto flipping there's no animation

flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);

doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);

How do I make a batch file terminate upon encountering an error?

Add || goto :label to each line, and then define a :label.

For example, create this .cmd file:

@echo off

echo Starting very complicated batch file...
ping -invalid-arg || goto :error
echo OH noes, this shouldn't have succeeded.
goto :EOF

:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

See also question about exiting batch file subroutine.

Is it possible to put a ConstraintLayout inside a ScrollView?

PROBLEM:

I had a problem with ConstraintLayout and ScrollView when i wanted to include it in another layout.

DECISION:

The solution to my problem was to use dataBinding.

dataBinding (layout)

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

How to make grep only match if the entire line matches?

    $ cat venky
    ABB.log
    ABB.log.122
    ABB.log.123

    $ cat venky | grep "ABB.log" | grep -v "ABB.log\."
    ABB.log
    $

    $ cat venky | grep "ABB.log.122" | grep -v "ABB.log.122\."
    ABB.log.122
    $

How to set up tmux so that it starts up with specified windows opened?

I've create this script. It does not need tmuxinator, ruby or others. It is just a bash script, configurable:

A file named config should contains something like this:

combo=()
combo+=('logs' 'cd /var/log; clear; pwd')
combo+=('home' 'cd ~; clear; pwd')

and the bash code should be:

#!/bin/bash

if [ -r config ]; then
    echo ""
    echo "Loading custom file"
    . config
else
    . config.dist
fi

tmux start-server

window=0
windownumber=-1

for i in "${combo[@]}"; do

    if [ $((window%2)) == 0 ]; then
        name=${i}
        ((windownumber++))
    else
        command=${i}
    fi

    if [ ${combo[0]} == "${i}" ]; then
        tmux new-session -d -s StarTmux -n "${name}"
    else
        if [ $((window%2)) == 0 ]; then
            tmux new-window -tStarTmux:$windownumber -n "${name}"
        fi
    fi

    if [ $((window%2)) == 1 ]; then
        tmux send-keys -tStarTmux:$windownumber "${command}" C-m
    fi

    ((window++))
done

tmux select-window -tStarTmux:0
tmux attach-session -d -tStarTmux

How do I create a new branch?

Branches in SVN are essentially directories; you don't name the branch so much as choose the name of the directory to branch into.

The common way of 'naming' a branch is to place it under a directory called branches in your repository. In the "To URL:" portion of TortoiseSVN's Branch dialog, you would therefore enter something like:

(svn/http)://path-to-repo/branches/your-branch-name

The main branch of a project is referred to as the trunk, and is usually located in:

(svn/http)://path-to-repo/trunk

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

jQuery if Element has an ID?

I seemed to have been able to solve it with:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

I want to get the type of a variable at runtime

i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

Determining complexity for recursive functions (Big O notation)

The time complexity, in Big O notation, for each function:


int recursiveFun1(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun1(n-1);
}

This function is being called recursively n times before reaching the base case so its O(n), often called linear.


int recursiveFun2(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun2(n-5);
}

This function is called n-5 for each time, so we deduct five from n before calling the function, but n-5 is also O(n). (Actually called order of n/5 times. And, O(n/5) = O(n) ).


int recursiveFun3(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun3(n/5);
}

This function is log(n) base 5, for every time we divide by 5 before calling the function so its O(log(n))(base 5), often called logarithmic and most often Big O notation and complexity analysis uses base 2.


void recursiveFun4(int n, int m, int o)
{
    if (n <= 0)
    {
        printf("%d, %d\n",m, o);
    }
    else
    {
        recursiveFun4(n-1, m+1, o);
        recursiveFun4(n-1, m, o+1);
    }
}

Here, it's O(2^n), or exponential, since each function call calls itself twice unless it has been recursed n times.



int recursiveFun5(int n)
{
    for (i = 0; i < n; i += 2) {
        // do something
    }

    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun5(n-5);
}

And here the for loop takes n/2 since we're increasing by 2, and the recursion takes n/5 and since the for loop is called recursively, therefore, the time complexity is in

(n/5) * (n/2) = n^2/10,

due to Asymptotic behavior and worst-case scenario considerations or the upper bound that big O is striving for, we are only interested in the largest term so O(n^2).


Good luck on your midterms ;)

Python regex findall

you can replace your pattern with

regex = ur"\[P\]([\w\s]+)\[\/P\]"

Save bitmap to location

After Android 4.4 Kitkat, and as of 2017 share of Android 4.4 and less is about 20% and decreasing, it's not possible to save to SD card using File class and getExternalStorageDirectory() method. This method returns your device internal memory and images save visible to every app. You can also save images only private to your app and to be deleted when user deletes your app with openFileOutput() method.

Starting with Android 6.0, you can format your SD card as an internal memory but only private to your device.(If you format SD car as internal memory, only your device can access or see it's contents) You can save to that SD card using other answers but if you want to use a removable SD card you should read my answer below.

You should use Storage Access Framework to get uri to folder onActivityResult method of activity to get folder selected by user, and add retreive persistiable permission to be able to access folder after user restarts the device.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {

        // selectDirectory() invoked
        if (requestCode == REQUEST_FOLDER_ACCESS) {

            if (data.getData() != null) {
                Uri treeUri = data.getData();
                tvSAF.setText("Dir: " + data.getData().toString());
                currentFolder = treeUri.toString();
                saveCurrentFolderToPrefs();

                // grantUriPermission(getPackageName(), treeUri,
                // Intent.FLAG_GRANT_READ_URI_PERMISSION |
                // Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                final int takeFlags = data.getFlags()
                        & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Check for the freshest data.
                getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

            }
        }
    }
}

Now, save save folder to shared preferences not to ask user to select folder every time you want to save an image.

You should use DocumentFile class to save your image, not File or ParcelFileDescriptor, for more info you can check this thread for saving image to SD card with compress(CompressFormat.JPEG, 100, out); method and DocumentFile classes.

What is a blob URL and why it is used?

Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN and method name) are used with a Blob or a File object.

src="blob:https://crap.crap" I opened the blob url that was in src of video it gave a error and i can't open but was working with the src tag how it is possible?

Blob URLs can only be generated internally by the browser. URL.createObjectURL() will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL(). These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).

What is blob url?
Why it is used?

Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.

For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.

It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.

Can i make my own blob url on a server?

No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.

if you have then Additional detail

You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL() to generate a local URL for it:

var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
    url = URL.createObjectURL(blob),
    img = new Image();

img.onload = function() {
    URL.revokeObjectURL(this.src);     // clean-up memory
    document.body.appendChild(this);   // add image to DOM
}

img.src = url;                         // can now "stream" the bytes

Note that URL may be prefixed in webkit-browsers, so use:

var url = (URL || webkitURL).createObjectURL(...);

Bower: ENOGIT Git is not installed or not in the PATH

Adding Git to Windows 7/8/8.1 Path

Note: You must have msysgit installed on your machine. Also, the path to my Git installation is "C:\Program Files (x86)\Git". Yours might be different. Please check where yours is before continuing.

Open the Windows Environment Variables/Path Window.

  1. Right-click on My Computer -> Properties
  2. Click Advanced System Settings link from the left side column
  3. Click Environment Variables in the bottom of the window
  4. Then under System Variables look for the path variable and click edit
  5. Add the pwd to Git's binary and cmd at the end of the string like this:

    ;%PROGRAMFILES(x86)%\Git\bin;%PROGRAMFILES(x86)%\Git\cmd
    

Now test it out in PowerShell. Type git and see if it recognizes the command.

This is image showing you how to do so!

Source: Adding Git to Windows 7 Path

Sequence contains no elements?

In addition to everything else that has been said, you can call DefaultIfEmpty() before you call Single(). This will ensure that your sequence contains something and thereby averts the InvalidOperationException "Sequence contains no elements". For example:

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).DefaultIfEmpty().Single();

How to set the value for Radio Buttons When edit?

When you populate your fields, you can check for the value:

<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female

Assuming that the value you return from your database is in the variable $sex

The checked property will preselect the value that match

How can I remove an SSH key?

I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.

How to round an image with Glide library?

In this case I need add shadows, and imageView elevation not working

implementation "com.github.bumptech.glide:glide:4.10.0"

XML

<FrameLayout
    android:id="@+id/fl_image"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_margin="10dp"
    android:background="@drawable/card_circle_background"
    android:elevation="8dp">

    <ImageView
        android:id="@+id/iv_item_employee"
        android:layout_width="60dp"
        android:layout_height="60dp"
        tools:background="@color/colorPrimary" />
</FrameLayout>

Shape drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
     <solid android:color="@color/white"/>
</shape>

Glide Configuration

Glide.with(this)
    .asBitmap()
    .load(item.image)
    .apply(RequestOptions.circleCropTransform())
    .into(iv_item_employee)

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Managing jQuery plugin dependency in webpack

I don't know if I understand very well what you are trying to do, but I had to use jQuery plugins that required jQuery to be in the global context (window) and I put the following in my entry.js:

var $ = require('jquery');
window.jQuery = $;
window.$ = $;

The I just have to require wherever i want the jqueryplugin.min.js and window.$ is extended with the plugin as expected.

Executing set of SQL queries using batch file?

Different ways:

  1. Using SQL Server Agent (If local instance)
    schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.

  2. Using SQLCMD
    To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx

  3. Using SQLPS
    To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx

How can I stop python.exe from closing immediately after I get an output?

It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:\> cd C:\my_programs\
C:\my_programs\> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How can I copy data from one column to another in the same table?

How about this

UPDATE table SET columnB = columnA;

This will update every row.

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

How to get Map data using JDBCTemplate.queryForMap

I know this is really old, but this is the simplest way to query for Map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

git: 'credential-cache' is not a git command

A similar error is 'credential-wincred' is not a git command

The accepted and popular answers are now out of date...

wincred is for the project git-credential-winstore which is no longer maintained.

It was replaced by Git-Credential-Manager-for-Windows maintained by Microsoft open source.

Download the release as zip file from link above and extract contents to

\cygwin\usr\libexec\git-core

(or \cygwin64\usr\libexec\git-core as it may be)

Then enable it, (by setting the global .gitconfig) - execute:

git config --global credential.helper manager

How to use

No further config is needed.

It works [automatically] when credentials are needed.

For example, when pushing to Azure DevOps, it opens a window and initializes an oauth2 flow to get your token.

ref:

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

How do I unbind "hover" in jQuery?

$(this).unbind('mouseenter').unbind('mouseleave')

or more succinctly (thanks @Chad Grant):

$(this).unbind('mouseenter mouseleave')

Create SQL script that create database and tables

Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.

For unordered scripts generated by SSMS you can go following

a) Execute script (some objects will be inserted some wont, there will be some errors)

b) Remove all objects from the script that have been added to database

c) Go back to a) until everything is eventually executed

Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).

All of these will take care of the dependencies for you and save you even more time.

Best Way to read rss feed in .net Using C#

This is an old post, but to save people some time if you get here now like I did, I suggest you have a look at the CodeHollow.FeedReader package which supports a wider range of RSS versions, is easier to use and seems more robust. https://github.com/codehollow/FeedReader

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

gsub("\\..*","",a)
[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Generally speaking:

F5 may give you the same page even if the content is changed, because it may load the page from cache. But Ctrl-F5 forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.

Leave out quotes when copying from cell

First paste it into Word, then you can paste it into notepad and it will appear without the quotes

How to call loading function with React useEffect only once

useMountEffect hook

Running a function only once after component mounts is such a common pattern that it justifies a hook of it's own that hides implementation details.

const useMountEffect = (fun) => useEffect(fun, [])

Use it in any functional component.

function MyComponent() {
    useMountEffect(function) // function will run only once after it has mounted. 
    return <div>...</div>;
}

About the useMountEffect hook

When using useEffect with a second array argument, React will run the callback after mounting (initial render) and after values in the array have changed. Since we pass an empty array, it will run only after mounting.

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Core dumped, but core file is not in the current directory?

If you're missing core dumps for binaries on RHEL and when using abrt, make sure that /etc/abrt/abrt-action-save-package-data.conf

contains

ProcessUnpackaged = yes

This enables the creation of crash reports (including core dumps) for binaries which are not part of installed packages (e.g. locally built).

In C#, what is the difference between public, private, protected, and having no access modifier?

A graphical overview (summary in a nutshell)

Visibility

Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.



For the defaults if you put no access modifier in front, see here:
Default visibility for C# classes and members (fields, methods, etc.)?

Non-nested

enum                              public
non-nested classes / structs      internal
interfaces                        internal
delegates in namespace            internal
class/struct member(s)            private
delegates nested in class/struct  private

Nested:

nested enum      public
nested interface public
nested class     private
nested struct    private

Also, there is the sealed-keyword, which makes a class not-inheritable.
Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:

VB vs. CS equivalents

Get key and value of object in JavaScript?

$.each(top_brands, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  brand_options.append($("<option />").val(key).text(key + " "  + value));
});

tqdm in Jupyter Notebook prints new progress bars repeatedly

Use tqdm_notebook

from tqdm import tqdm_notebook as tqdm

x=[1,2,3,4,5]

for i in tqdm(range(0,len(x))):

    print(x[i])

Twitter Bootstrap alert message close and open again

All of the above solutions use external libraries, either angular or jQuery, and an old version of Bootstrap. So, here is Charles Wyke-Smith's solution in pure JavaScript, applied to Bootstrap 4. Yes, Bootstrap requires jQuery for its own modal and alerts code, but not everyone writes their own code with jQuery any more.

Here is the html of the alert:

<div id="myAlert" style="display: none;" 
    class="alert alert-success alert-dismissible fade show">
    <button type="button" class="close" data-hide="alert">&times;</button>
    <strong>Success!</strong> You did it!
</div>

Note that initially the alert is hidden (style="display: none;"), and instead of the standard data-dismiss="alert", we have here used data-hide="alert".

Here is the JavaScript to show the alert and override the close button:

var myAlert = document.getElementById('myAlert');
// Show the alert box
myAlert.style.display = 'block';
// Override Bootstrap's standard close action
myAlert.querySelector('button[data-hide]').addEventListener('click', function() {
    myAlert.style.display = 'none';
});

If you wish to hide or show the alert programmatically elsewhere in the code, just do myAlert.style.display = 'none'; or myAlert.style.display = 'block';.

Add resources, config files to your jar using gradle

I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:

sourceSets {
    main {
        resources {
            srcDirs "src/main/resources", "src/main/configs"
        }
    }
}

How to find the location of the Scheduled Tasks folder

I want to extend @Jan answer:

It's seems, that Task Scheduler 1.0 API uses C:\Windows\Tasks folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API uses C:\Windows\System32\Tasks to create and enumerate tasks (this example).

It's also seems, that windows console utility schtasks and GUI utility taskschd.msc uses Task Scheduler 2.0 API.

P.S. I found, that if task placed in C:\Windows\Tasks and have not set AccountInformation, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation (even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON - task will be displayed in all standard applications.

Solution found here

How to set bootstrap navbar active class with Angular JS?

Extending myl answer, I needed this to handle an structure like this.

-index

-events<-active
---event-list
---event-edit
---event-map <-clicked

-places
---place-list
---place-edit
---place-map

so instead of matching, I had to use indexOf, in order to validate children links which are formatted to match the condition. So for 'events':

<li ng-class="{ active: isActive('/event')}" class="divider-vertical dropdown">


function NavController($scope, $location) { 
$scope.isActive = function (viewLocation) {
    var s=false;
    if($location.path().indexOf(viewLocation) != -1){
     s = true;
    }
    return s;
};}

Change the maximum upload file size

the answers are a bit incomplete, 3 things you have to do

in php.ini of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate. For nginx it is usually located in /etc/php/7.1/fpm where 7.1 depends on your version. For apache usually /etc/php/7.1/apache2)

post_max_size=500M

upload_max_filesize=500M

memory_limit=900M

or set other values. Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY 13 DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

open existing java project in eclipse

Eclipse does not have internal Subversion connectivity. After you've downloaded and unzipped Eclipse, you have to install a Subversion plug-in. Check with the other developers as to which Subversion plug-in you're using. Subclipse is one Subversion plug-in.

After you've installed the Subversion plug-in, you have to give Eclipse the repository information in the SVN Repositories view of the SVN Repositories perspective. One of the other developers should have that information.

Finally, you check out the project from Subversion, by left clicking on the Package Explorer, selecting New -> Project, and in the New Project wizard,left clicking on SVN -> Checkout projects from SVN.

How to update a single pod without touching other dependencies

Just a small notice.

pod update POD_NAME

will work only if this pod was already installed. Otherwise you will have to update all of them with

pod update

command

Bootstrap: Open Another Modal in Modal

The answer given by H Dog is great, but this approach was actually giving me some modal flicker in Internet Explorer 11. Bootstrap will first hide the modal removing the 'modal-open' class, and then (using H Dogs solution) we add the 'modal-open' class again. I suspect this is somehow causing the flicker I was seeing, maybe due to some slow HTML/CSS rendering.

Another solution is to prevent bootstrap in removing the 'modal-open' class from the body element in the first place. Using Bootstrap 3.3.7, this override of the internal hideModal function works perfectly for me.

$.fn.modal.Constructor.prototype.hideModal = function () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
        if ($(".modal:visible").length === 0) {
            that.$body.removeClass('modal-open')
        }
        that.resetAdjustments()
        that.resetScrollbar()
        that.$element.trigger('hidden.bs.modal')
    })
}

In this override, the 'modal-open' class is only removed when there are no visible modals on the screen. And you prevent one frame of removing and adding a class to the body element.

Just include the override after bootstrap have been loaded.

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

Reflection - get attribute name and value on property

Necromancing.
For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:

public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
{
    object[] objs = mi.GetCustomAttributes(t, true);

    if (objs == null || objs.Length < 1)
        return null;

    return objs[0];
}



public static T GetAttribute<T>(System.Reflection.MemberInfo mi)
{
    return (T)GetAttribute(mi, typeof(T));
}


public delegate TResult GetValue_t<in T, out TResult>(T arg1);

public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute
{
    TAttribute[] objAtts = (TAttribute[])mi.GetCustomAttributes(typeof(TAttribute), true);
    TAttribute att = (objAtts == null || objAtts.Length < 1) ? default(TAttribute) : objAtts[0];
    // TAttribute att = (TAttribute)GetAttribute(mi, typeof(TAttribute));

    if (att != null)
    {
        return value(att);
    }
    return default(TValue);
}

Example usage:

System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a){ return a.Name;});

or simply

string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

Pytorch tensor to numpy array

This worked for me:

np_arr = torch_tensor.cpu().detach().numpy()

Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

Allow a div to cover the whole page instead of the area within the container

#dimScreen{
 position:fixed;
 top:0px;
 left:0px;
 width:100%;
 height:100%;
}

How can I install Apache Ant on Mac OS X?

If you're a homebrew user instead of macports, homebrew has an ant recipe.

brew install ant

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

How to fetch Java version using single line command in Linux

  1. Redirect stderr to stdout.
  2. Get first line
  3. Filter the version number.

    java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
    

Regular expression for extracting tag attributes

I'd reconsider the strategy to use only a single regular expression. Sure it's a nice game to come up with one single regular expression that does it all. But in terms of maintainabilty you are about to shoot yourself in both feet.

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

How to use Console.WriteLine in ASP.NET (C#) during debug?

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

How to list the contents of a package using YUM?

There are several good answers here, so let me provide a terrible one:

: you can type in anything below, doesnt have to match anything

yum whatprovides "me with a life"

: result of the above (some liberties taken with spacing):

Loaded plugins: fastestmirror
base | 3.6 kB 00:00 
extras | 3.4 kB 00:00 
updates | 3.4 kB 00:00 
(1/4): extras/7/x86_64/primary_db | 166 kB 00:00 
(2/4): base/7/x86_64/group_gz | 155 kB 00:00 
(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04 
(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05 
Determining fastest mirrors
 * base: mirrors.xmission.com
 * extras: mirrors.xmission.com
 * updates: mirrors.xmission.com
base/7/x86_64/filelists_db | 6.2 MB 00:02 
extras/7/x86_64/filelists_db | 468 kB 00:00 
updates/7/x86_64/filelists_db | 5.3 MB 00:01 
No matches found

: the key result above is that "primary_db" files were downloaded

: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf

: note you can limit this to "primary_db.sqlite" if you really want

find /var/cache/yum -name '*.sqlite'

: if you download/install a new repo, run the exact same command again
: to get the databases for the new repo

: if you know sqlite you can stop reading here

: if not heres a sample command to dump the contents

echo 'SELECT packages.name, GROUP_CONCAT(files.name, ", ") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite 

: remove "LIMIT 10" above for the whole list

: format chosen for proof-of-concept purposes, probably can be improved a lot

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

jQuery if checkbox is checked

for jQuery 1.6 or higher:

if ($('input.checkbox_check').prop('checked')) {
    //blah blah
}

the cross-browser-compatible way to determine if a checkbox is checked is to use the property https://api.jquery.com/prop/

Truncate all tables in a MySQL database in one command?

  1. To truncate a table, one must drop the foreign key constraints mapped to the columns in this table from other tables (in fact on all tables in the specific DB/Schema).
  2. So, all foreign key constraints must be dropped initially followed by table truncation.
  3. Optionally, use the optimize table (in mysql, innodb engine esp) to reclaim the used data space/size to OS after data truncation.
  4. Once data truncation is carried out, create the same foreign key constraints again on the same table. See below a script that would generate the script to carry out the above operations.

    SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME,';') FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE='FOREIGN KEY' AND TABLE_SCHEMA='<TABLE SCHEMA>'
    UNION
    SELECT CONCAT('TRUNCATE TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,';') FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='<TABLE SCHEMA>' AND TABLE_TYPE='BASE TABLE'
    UNION
    SELECT CONCAT('OPTIMIZE TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,';') FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='<TABLE SCHEMA>' AND TABLE_TYPE='BASE TABLE'
    UNION
    SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' ADD CONSTRAINT ',CONSTRAINT_NAME,' FOREIGN KEY(',COLUMN_NAME,')',' REFERENCES ',REFERENCED_TABLE_NAME,'(',REFERENCED_COLUMN_NAME,');') FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE CONSTRAINT_NAME LIKE 'FK%' AND TABLE_SCHEMA='<TABLE SCHEMA>'
    INTO OUTFILE "C:/DB Truncate.sql" LINES TERMINATED BY '\n';
    

Now, run the Db Truncate.sql script generated

Benefits. 1) Reclaim disk space 2) Not needed to drop and recreate the DB/Schema with the same structure

Drawbacks. 1) FK constraints should be names in the table with the name containing 'FK' in the constraint name.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

How to get status code from webclient?

Just in case someone else needs an F# version of the above described hack.

open System
open System.IO
open System.Net

type WebClientEx() =
     inherit WebClient ()
     [<DefaultValue>] val mutable m_Resp : WebResponse

     override x.GetWebResponse (req: WebRequest ) =
        x.m_Resp <- base.GetWebResponse(req)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;
        x.m_Resp

     override x.GetWebResponse (req: WebRequest , ar: IAsyncResult  ) =
        x.m_Resp <- base.GetWebResponse(req, ar)
        (req :?> HttpWebRequest).AllowAutoRedirect <- false;
        x.m_Resp

     member x.StatusCode with get() : HttpStatusCode = 
            if not (obj.ReferenceEquals (x.m_Resp, null)) && x.m_Resp.GetType() = typeof<HttpWebResponse> then
                (x.m_Resp :?> HttpWebResponse).StatusCode
            else
                HttpStatusCode.OK

let wc = new WebClientEx()
let st = wc.OpenRead("http://www.stackoverflow.com")
let sr = new StreamReader(st)
let res = sr.ReadToEnd()
wc.StatusCode
sr.Close()
st.Close()

Android: converting String to int

try this

String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());

boolean ins = myDB.adddata(t1,t2);

public boolean adddata(String name, Integer price)

How do I make a JSON object with multiple arrays?

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

See:

CSS fill remaining width

I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:

http://jsbin.com/hapelawake

How do I make a PHP form that submits to self?

Try this

<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"

Works well :)

The remote host closed the connection. The error code is 0x800704CD

One can reproduce the error with the code below:

public ActionResult ClosingTheConnectionAction(){
   try
   {
      //we need to set buffer to false to
      //make sure data is written in chunks
      Response.Buffer = false;  
      var someText = "Some text here to make things happen ;-)";
      var content = GetBytes( someText );

      for(var i=0; i < 100; i++)
      {
         Response.OutputStream.Write(content, 0, content.Length);
      }

      return View();
   }
   catch(HttpException hex)
   {
      if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
            {
                //react on remote host closed the connection exception.
                var msg = hex.Message;
            }  
   }
   catch(Exception somethingElseHappened)
   {
      //handle it with some other code
   }

   return View();
} 

Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)

java.io.IOException: Broken pipe

The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.

If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.

Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.

FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.

How to search a Git repository by commit message?

I put this in my ~/.gitconfig:

[alias]
    find = log --pretty=\"format:%Cgreen%H %Cblue%s\" --name-status --grep

Then I can type "git find string" and I get a list of all the commits containing that string in the message. For example, to find all commits referencing ticket #33:

029a641667d6d92e16deccae7ebdeef792d8336b Added isAttachmentEditable() and isAttachmentViewable() methods. (references #33)
M       library/Dbs/Db/Row/Login.php

a1bccdcd29ed29573d2fb799e2a564b5419af2e2 Add permissions checks for attachments of custom strategies. (references #33).
M       application/controllers/AttachmentController.php

38c8db557e5ec0963a7292aef0220ad1088f518d Fix permissions. (references #33)
M       application/views/scripts/attachment/_row.phtml

041db110859e7259caeffd3fed7a3d7b18a3d564 Fix permissions. (references #33)
M       application/views/scripts/attachment/index.phtml

388df3b4faae50f8a8d8beb85750dd0aa67736ed Added getStrategy() method. (references #33)
M       library/Dbs/Db/Row/Attachment.php

Why am I getting this redefinition of class error?

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
{
    x = inx;
    y = iny;
}

int gameObject::add()
{
    return x+y;
}

etc

How to use pip with python 3.4 on windows?

"py -m pip install requests" works fine with Windows and its up gradation. Just change the path after installing Python 3.4 in the command prompt and type in "py -m pip install requests"command prompt. pip install

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

Capture event onclose browser

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

How to fix a header on scroll

The simplest way is: HTML:

<header>
        <h1>Website</h1>
</header>

CSS:

header{
    position: sticky;
    top: 0;
}

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

Get single listView SelectedItem

Usually SelectedItems returns either a collection, an array or an IQueryable.

Either way you can access items via the index as with an array:

String text = listView1.SelectedItems[0].Text; 

By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.

Conda command is not recognized on Windows 10

If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.

Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

React - How to get parameter value from query string?

do it all in one line without 3rd party libraries or complicated solutions. Here is how

let myVariable = new URLSearchParams(history.location.search).get('business');

the only thing you need to change is the word 'business' with your own param name.

example url.com?business=hello

the result of myVariable will be hello

Linux: copy and create destination dir if it does not exist

Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }

What is the most compatible way to install python modules on a Mac?

Please see Python OS X development environment. The best way is to use MacPorts. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:

sudo port install python26 python_select
sudo port select --set python python26

OR

sudo port install python30 python_select
sudo port select --set python python30

Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:

sudo port install py26-packagename

OR

sudo port install py30-packagename

In the above commands, replace packagename with the name of the package, for example:

sudo port install py26-setuptools

These commands will automatically install the package (and its dependencies) for the given Python version.

For a full list of available packages for Python, type:

port list | grep py26-

OR

port list | grep py30-

Which command you use depends on which version of Python you chose to install.

Java Enum return Int

You can try this code .

private enum DownloadType {
    AUDIO , VIDEO , AUDIO_AND_VIDEO ;

}

You can use this enumeration as like this : DownloadType.AUDIO.ordinal(). Hope this code snippet will help you .

Mipmap drawables for icons

The Android implementation of mipmaps in 4.3 is exactly the technique from 1983 explained in the Wikipedia article :)

Each bitmap image of the mipmap set is a downsized duplicate of the main texture, but at a certain reduced level of detail. Although the main texture would still be used when the view is sufficient to render it in full detail, the renderer will switch to a suitable mipmap image (...) when the texture is viewed from a distance or at a small size.

Although this is described as a technique for 3D graphics (as it mentions "viewing from a distance"), it applies just as well to 2D (translated as "drawn is a smaller space", i.e. "downscaled").

For a concrete Android example, imagine you have a View with a certain background drawable (in particular, a BitmapDrawable). You now use an animation to scale it to 0.15 of its original size. Normally, this would require downscaling the background bitmap for each frame. This "extreme" downscaling, however, may produce visual artifacts.

You can, however, provide a mipmap, which means that the image is already pre-rendered for a few specific scales (let's say 1.0, 0.5, and 0.25). Whenever the animation "crosses" the 0.5 threshold, instead of continuing to downscale the original, 1.0-sized image, it will switch to the 0.5 image and downscale it, which should provide a better result. And so forth as the animation continues.

This is a bit theoretical, since it's actually done by the renderer. According to the source of the Bitmap class, it's just a hint, and the renderer may or may not honor it.

/**
 * Set a hint for the renderer responsible for drawing this bitmap
 * indicating that it should attempt to use mipmaps when this bitmap
 * is drawn scaled down.
 *
 * If you know that you are going to draw this bitmap at less than
 * 50% of its original size, you may be able to obtain a higher
 * quality by turning this property on.
 * 
 * Note that if the renderer respects this hint it might have to
 * allocate extra memory to hold the mipmap levels for this bitmap.
 *
 * This property is only a suggestion that can be ignored by the
 * renderer. It is not guaranteed to have any effect.
 *
 * @param hasMipMap indicates whether the renderer should attempt
 *                  to use mipmaps
 *
 * @see #hasMipMap()
 */
public final void setHasMipMap(boolean hasMipMap) {
    nativeSetHasMipMap(mNativeBitmap, hasMipMap);
}

I'm not quite sure why this would be especially suitable for application icons, though. Although Android on tablets, as well as some launchers (e.g. GEL), request an icon "one density higher" to show it bigger, this is supposed to be done using the regular mechanism (i.e. drawable-xxxhdpi, &c).

How to save and load cookies using Python + Selenium WebDriver

This is code I used in Windows. It works.

for item in COOKIES.split(';'):
    name,value = item.split('=', 1)
    name=name.replace(' ', '').replace('\r', '').replace('\n', '')
    value = value.replace(' ', '').replace('\r', '').replace('\n', '')
    cookie_dict={
            'name':name,
            'value':value,
            "domain": "",  # Google Chrome
            "expires": "",
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
    self.driver_.add_cookie(cookie_dict)

How to add calendar events in Android?

you have to add flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

Change jsp on button click

It works using ajax. The jsp then display in iframe returned by controller in response to request.

function openPage() {
  jQuery.ajax({
  type : 'POST',
  data : jQuery(this).serialize(),
  url : '<%=request.getContextPath()%>/post_action',
  success : function(data, textStatus) {
  jQuery('#iframeId').contents().find('body').append(data);
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
  }
  });
}

Angular 2 - Setting selected value on dropdown list

In my case i was returning string value from my api eg: "35" and in my HTML i was using

       <mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
            <mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
              {{ state.stateName }}
            </mat-option>
          </mat-select>

Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below

          var x = user.state;
          var y: number = +x;

and then assigned it like

  this.EditProfileForm.get('states').setValue(y);

Now the correct values is getting setting by default.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I am using this workaround: Fix bg1's height on page load by:

var BG = document.getElementById('bg1');
BG.style.height = BG.parentElement.clientHeight;

Then attach a resize event listener to Window which does this: if difference in height after resizing is less than 60px (anything more than url bar height) then do nothing and if it is greater than 60px then set bg1's height again to its parent's height! complete code:

window.addEventListener("resize", onResize, false);
var BG = document.getElementById('bg1');
BG.style.height = BG.parentElement.clientHeight;
var oldH = BG.parentElement.clientHeight;

function onResize() {
    if(Math.abs(oldH - BG.parentElement.clientHeight) > 60){
      BG.style.height = BG.parentElement.clientHeight + 'px';
      oldH = BG.parentElement.clientHeight;
    }
}

PS: This bug is so irritating!

Can I do Model->where('id', ARRAY) multiple where conditions?

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();

or:

$items = DB::table('items')->whereIn('id',[1,2,..])->get();

How do I sort a vector of pairs based on the second element of the pair?

You can use boost like this:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Segmentation Fault - C

s is an uninitialized pointer; you are writing to a random location in memory. This will invoke undefined behaviour.

You need to allocate some memory for s. Also, never use gets; there is no way to prevent it overflowing the memory you allocate. Use fgets instead.

Appending a line break to an output file in a shell script

I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:

echo "`date` User `whoami` started the script."$'\r' >> output.log

(where the $'\r' at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).

What is the difference between an expression and a statement in Python?

Expressions:

  • Expressions are formed by combining objects and operators.
  • An expression has a value, which has a type.
  • Syntax for a simple expression:<object><operator><object>

2.0 + 3 is an expression which evaluates to 5.0 and has a type float associated with it.

Statements

Statements are composed of expression(s). It can span multiple lines.

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

Base64 length calculation?

If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:

const getBase64Size = (base64) => {
  let padding = base64.length
    ? getBase64Padding(base64)
    : 0
  return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}

const getBase64Padding = (base64) => {
  return endsWith(base64, '==')
    ? 2
    : 1
}

const endsWith = (str, end) => {
  let charsFromEnd = end.length
  let extractedEnd = str.slice(-charsFromEnd)
  return extractedEnd === end
}

How do I access call log for android?

Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en

Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.

This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.

I wish you good luck of cause with your applications guys but be careful.

How to display data from database into textbox, and update it

protected void Page_Load(object sender, EventArgs e)

    {

        DropDownTitle();
    }


protected void DropDownTitle()
{
    if (!Page.IsPostBack)
    {

        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;

        string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;
        try
        {

            ListItem newItem = new ListItem();
            newItem.Text = "Select";
            newItem.Value = "0";
            ForumTitleList.Items.Add(newItem);
            con.Open();
            reader = cmd.ExecuteReader();



            while (reader.Read())
            {
                ListItem newItem1 = new ListItem();
                newItem1.Text = reader["ForumTitles"].ToString();
                newItem1.Value = reader["ForumTitlesID"].ToString();
                ForumTitleList.Items.Add(newItem1);



            }
            reader.Close();
            reader.Dispose();
            con.Close();
            con.Dispose();
            cmd.Dispose();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }
}

How to create a zip archive with PowerShell?

Lot has changed since the initial answer was posted. Here are some of the latest examples using Compress-Archive command.

Command to create new archive file, Draft.zip, by compressing two files, Draftdoc.docx and diagram2.vsd, specified by the Path parameter. The compression level specified for this operation is Optimal.

Compress-Archive -Path C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip

Command to creates new archive file, Draft.zip, by compressing two files, Draft doc.docx and Diagram [2].vsd, specified by the LiteralPath parameter. The compression level specified for this operation is Optimal.

Compress-Archive -LiteralPath 'C:\Reference\Draft Doc.docx', 'C:\Reference\Images\Diagram [2].vsd'  -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip

Command to create new archive file, Draft.zip, in the C:\Archives folder. The new archive file contains every file in the C:\Reference folder, because a wildcard character was used in place of specific file names in the Path parameter.

Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft

Command creates an archive from an entire folder, C:\Reference

Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft

PowerShell appends the .zip extension to the file name automatically.

How to detect orientation change in layout in Android?

If accepted answer doesn't work for you, make sure you didn't define in manifest file:

android:screenOrientation="portrait"

Which is my case.

Bind event to right mouse click

I found this answer here and I'm using it like this.

Code from my Library:

$.fn.customContextMenu = function(callBack){
    $(this).each(function(){
        $(this).bind("contextmenu",function(e){
             e.preventDefault();
             callBack();
        });
    }); 
}

Code from my page's script:

$("#newmagazine").customContextMenu(function(){
    alert("some code");
});

Increasing (or decreasing) the memory available to R processes

  1. Buy more ram
  2. Switch to a 64-bit OS. Combine with point 1.

How to check if multiple array keys exists

I am not sure, if it is bad idea but I use very simple foreach loop to check multiple array key.

// get post attachment source url
$image     = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'single-post-thumbnail');
// read exif data
$tech_info = exif_read_data($image[0]);

// set require keys
$keys = array('Make', 'Model');

// run loop to add post metas foreach key
foreach ($keys as $key => $value)
{
    if (array_key_exists($value, $tech_info))
    {
        // add/update post meta
        update_post_meta($post_id, MPC_PREFIX . $value, $tech_info[$value]);
    }
} 

How do you set the max number of characters for an EditText in Android?

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_edittext_length"