Programs & Examples On #Ssis

SSIS (Microsoft SQL Server Integration Services) is a platform for building enterprise-level data integration and data transformations solutions. SSIS is used to perform ETL operations; i.e. extract, transform and load data.

Temporarily disable all foreign key constraints

To disable foreign key constraints:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS 
(
  SELECT DISTINCT obj = 
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' 
    + QUOTENAME(OBJECT_NAME(parent_object_id)) 
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' NOCHECK CONSTRAINT ALL;
' FROM x;

EXEC sp_executesql @sql;

To re-enable:

DECLARE @sql NVARCHAR(MAX) = N'';

;WITH x AS 
(
  SELECT DISTINCT obj = 
      QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' 
    + QUOTENAME(OBJECT_NAME(parent_object_id)) 
  FROM sys.foreign_keys
)
SELECT @sql += N'ALTER TABLE ' + obj + ' WITH CHECK CHECK CONSTRAINT ALL;
' FROM x;

EXEC sp_executesql @sql;

However, you will not be able to truncate the tables, you will have to delete from them in the right order. If you need to truncate them, you need to drop the constraints entirely, and re-create them. This is simple to do if your foreign key constraints are all simple, single-column constraints, but definitely more complex if there are multiple columns involved.

Here is something you can try. In order to make this a part of your SSIS package you'll need a place to store the FK definitions while the SSIS package runs (you won't be able to do this all in one script). So in some utility database, create a table:

CREATE TABLE dbo.PostCommand(cmd NVARCHAR(MAX));

Then in your database, you can have a stored procedure that does this:

DELETE other_database.dbo.PostCommand;

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id))
   + '.' + QUOTENAME(OBJECT_NAME(fk.parent_object_id)) 
   + ' ADD CONSTRAINT ' + fk.name + ' FOREIGN KEY (' 
   + STUFF((SELECT ',' + c.name
    FROM sys.columns AS c 
        INNER JOIN sys.foreign_key_columns AS fkc 
        ON fkc.parent_column_id = c.column_id
        AND fkc.parent_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
+ ') REFERENCES ' + 
QUOTENAME(OBJECT_SCHEMA_NAME(fk.referenced_object_id))
+ '.' + QUOTENAME(OBJECT_NAME(fk.referenced_object_id))
+ '(' + 
STUFF((SELECT ',' + c.name
    FROM sys.columns AS c 
        INNER JOIN sys.foreign_key_columns AS fkc 
        ON fkc.referenced_column_id = c.column_id
        AND fkc.referenced_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') + ');
' FROM sys.foreign_keys AS fk
WHERE OBJECTPROPERTY(parent_object_id, 'IsMsShipped') = 0;

INSERT other_database.dbo.PostCommand(cmd) SELECT @sql;

IF @@ROWCOUNT = 1
BEGIN
  SET @sql = N'';

  SELECT @sql += N'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(fk.parent_object_id)) 
    + ' DROP CONSTRAINT ' + fk.name + ';
  ' FROM sys.foreign_keys AS fk;

  EXEC sp_executesql @sql;
END

Now when your SSIS package is finished, it should call a different stored procedure, which does:

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = cmd FROM other_database.dbo.PostCommand;

EXEC sp_executesql @sql;

If you're doing all of this just for the sake of being able to truncate instead of delete, I suggest just taking the hit and running a delete. Maybe use bulk-logged recovery model to minimize the impact of the log. In general I don't see how this solution will be all that much faster than just using a delete in the right order.

In 2014 I published a more elaborate post about this here:

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

How to loop through Excel files and load them into a database using SSIS package?

I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.

If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.

The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Hope it helps.

SSIS how to set connection string dynamically from a config file

Some options:

  1. You can use the Execute Package Utility to change your datasource, before running the package.

  2. You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.

  3. You can use the SSIS XML package configuration file. Here is a walk through.

  4. You can save your configrations in a database table.

SSIS Excel Connection Manager failed to Connect to the Source

I also ran into this problem today, but found a different solution from using Excel 97-2003. According to Maderia, the problem is SSDT (SQL Server Data Tools) is a 32bit application and can only use 32bit providers; but you likely have the 64bit ACE OLE DB provider installed. You could play around with trying to install the 32bit provider, but you can't have both the 64 & 32 version installed at the same time. The solution Maderia suggested (and I found worked for me) was to set the DelayValidation = TRUE on the tasks where I'm importing/exporting the Excel 2007 file.

how to resolve DTS_E_OLEDBERROR. in ssis

I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.

Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008

http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx

http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx

http://blogs.msdn.com/b/psssql/archive/2008/10/01/windows-scalable-networking-pack-possible-performance-and-concurrency-impacts-to-sql-server-workloads.aspx

SSIS Connection Manager Not Storing SQL Password

Please check the configuration file in the project, set ID and password there, so that you execute the package

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

Microsoft.ACE.OLEDB.12.0 is not registered

The easiest solution I found was to specify excel version 97-2003 on the connection manager setup.

How do I edit SSIS package files?

I prefer to use :

(from SSDT visual studio just opened) file> open > file > locate dtsx file > open

then you can edit work and save

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

SSIS Excel Import Forcing Incorrect Column Type

  1. Click File on the ribbon menu, and then click on Options.
  2. Click Advanced, and then under When calculating this workbook, select the Set precision as displayed check box, and then click OK.

  3. Click OK.

  4. In the worksheet, select the cells that you want to format.

  5. On the Home tab, click the Dialog Box Launcher Button image next to Number.

  6. In the Category box, click Number.

  7. In the Decimal places box, enter the number of decimal places that you want to display.

How do I convert number to string and pass it as argument to Execute Process Task?

Cause of the issue:

Arguments property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR and not DT_STR.

SSIS 2008 R2 package illustrating the issue and fix:

Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx. Create a package variable with the following information.

Name   Scope        Data Type  Value
------ ------------ ---------- -----
IdVar  SO_13177007  Int32      123

Variables pane

Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments

Control Flow tab

Double-click the Execute Process Task to open the Execute Process Task Editor. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor.

Execute Process Task Editor

On the Property Expression Editor, select the property Arguments and click the Ellipsis button against the property to open the Expression Builder.

Property Expression Editor

On the Expression Builder, enter the following expression and click Evaluate Expression. This expression tries to convert the integer value in the variable IdVar to string data type.

(DT_STR, 10, 1252) @[User::IdVar]

Expression Builder - DT_STR

Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR.

Integer to ANSI string conversion error

To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR. Clicking Evaluate Expression will display the value in the Evaluated value text area.

(DT_WSTR, 10) @[User::IdVar]

Expression Builder - DT_WSTR

References:

To understand the differences between the data types DT_STR and DT_WSTR in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.

DT_STR

A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

DT_WSTR

A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

As a quick workaround I just saved the workbook as an Excel 97-2003 .xls file. I was able to import with that format with no error.

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

SSIS Text was truncated with status value 4

In my case, some of my rows didn't have the same number of columns as the header. Example, Header has 10 columns, and one of your rows has 8 or 9 columns. (Columns = Count number of you delimiter characters in each line)

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

SSIS Convert Between Unicode and Non-Unicode Error

  1. First, add a data conversion block into your data flow diagram.

  2. Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.

  3. Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.

  4. Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).

What is the SSIS package and what does it do?

Microsoft SQL Server Integration Services (SSIS) is a platform for building high-performance data integration solutions, including extraction, transformation, and load (ETL) packages for data warehousing. SSIS includes graphical tools and wizards for building and debugging packages; tasks for performing workflow functions such as FTP operations, executing SQL statements, and sending e-mail messages; data sources and destinations for extracting and loading data; transformations for cleaning, aggregating, merging, and copying data; a management database, SSISDB, for administering package execution and storage; and application programming interfaces (APIs) for programming the Integration Services object model.

As per Microsoft, the main uses of SSIS Package are:

• Merging Data from Heterogeneous Data Stores Populating Data

• Warehouses and Data Marts Cleaning and Standardizing Data Building

• Business Intelligence into a Data Transformation Process Automating

• Administrative Functions and Data Loading

For developers:

SSIS Package can be integrated with VS development environment for building Business Intelligence solutions. Business Intelligence Development Studio is the Visual Studio environment with enhancements that are specific to business intelligence solutions. It work with 32-bit development environment only.

Download SSDT tools for Visual Studio:

http://www.microsoft.com/en-us/download/details.aspx?id=36843

Creating SSIS ETL Package - Basics :

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

Sample project of SSIS features in 6 lessons:

https://docs.microsoft.com/en-us/sql/integration-services/ssis-how-to-create-an-etl-package?view=sql-server-2017

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

For me, I was accessing my XLS file from a network share. Moving the file for my connection manager to a local folder fixed the issue.

Convert from DateTime to INT

Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:

(DT_I8)FLOOR((DT_R8)systemDateTime)

But you'd have to test to doublecheck.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I know this is an old question. The way I solved it - after failing by increasing the length or even changing to data type text - was creating an XLSX file and importing. It accurately detected the data type instead of setting all columns as varchar(50). Turns out nvarchar(255) for that column would have done it too.

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.

How do I view the SSIS packages in SQL Server Management Studio?

  1. you could find it under intergration services option in object explorer.
  2. you could find the packages under integration services catalog where all packages are deployed.

How do I fix the multiple-step OLE DB operation errors in SSIS?

I had a similar issue when i was transferring data from an old database to a new database, I got the error above. I then ran the following script

SELECT * FROM [source].INFORMATION_SCHEMA.COLUMNS src INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst ON dst.COLUMN_NAME = src.COLUMN_NAME WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH

and found that my columns where slightly different in terms of character sizes etc. I then tried to alter the table to the new table structure which did not work. I then transferred the data from the old database into Excel and imported the data from excel to the new DB which worked 100%.

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

The value violated the integrity constraints for the column

It's as the error message says "The value violated the integrity constraints for the column" for column "Copy of F2"

Make it so it doesn't violate the value in the target table. What the allowable values are, data types, etc are not provided in your question so we cannot be more specific in answering.

To address the downvote, No, really it's as it says: you are putting something into a column that is not allowed. It could be Faizan points out, that you're putting a NULL into a NOT NULLable column, but it could be a whole host of other things and as the original poster never provided any update, we're left to guess. Was there a foreign key constraint that the insert violated? Maybe there's a check constraint that got blown? Maybe the source column in Excel has a valid date value for Excel that is not valid for the target column's date/time data type.

Thus, baring concrete information, the best possible answer is "don't do the thing that breaks it" In this case, something about "Copy of F2" is bad for the target column. Give us table definitions, supplied values, etc, then you can specific answers.

Telling people to make a NOT NULLable column into a NULLable one might be the right answer. It might also be the most horrific answer known to mankind. If an existing process expects there to always be a value in column "Copy of F2" changing the constraint to NULL can wreak havoc on existing queries. For example

SELECT * FROM ArbitraryTable AS T WHERE T.[Copy of F2] = '';

Currently, that query retrieves everything that was freshly imported because Copy of F2 is a poorly named status indicator. That data needs to get fed into the next system so... bills can get paid. As soon as you make it such that unprocessed rows can have a NULL value, the above query no longer satisfies that. Bills don't get paid, collections repos your building and now you're out of a job, all because you didn't do impact analysis, etc, etc.

How to execute an SSIS package from .NET?

Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.IntegrationServices;

public List<string> ExecutePackage(string folder, string project, string package)
{
    // Connection to the database server where the packages are located
    SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");

    // SSIS server object with connection
    IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

    // The reference to the package which you want to execute
    PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];

    // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
    Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();

    // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });

    // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });

    // Add a project parameter (value) to fill a project parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });

    // Add a project package (value) to fill a package parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });

    // Get the identifier of the execution to get the log
    long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

    // Loop through the log and do something with it like adding to a list
    var messages = new List<string>();
    foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
    {
        messages.Add(message.MessageType + ": " + message.Message);
    }

    return messages;
}

The code is a slight adaptation of http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage

There is also a similar article at http://domwritescode.com/2014/05/15/project-deployment-model-changes/

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

The dts data Conversion task is time taking if there are 50 plus columns!Found a fix for this at the below link

http://rdc.codeplex.com/releases/view/48420

However, it does not seem to work for versions above 2008. So this is how i had to work around the problem

*Open the .DTSX file on Notepad++. Choose language as XML
*Goto the <DTS:FlatFileColumns> tag. Select all items within this tag
*Find the string **DTS:DataType="129"**  replace with **DTS:DataType="130"**
*Save the .DTSX file. 
*Open the project again on Visual Studio BIDS
*Double Click on the Source Task . You would get the message

the metadata of the following output columns does not match the metadata of the external columns with which the output columns are associated:
...
Do you want to replace the metadata of the output columns with the metadata of the external columns?

 *Now Click Yes. We are done !

SSIS Connection not found in package

In my case, I could solve this in an easier way. I opened the x.dtsConfig archive, and for an unknown reason this archive was not in the standard format, so ssis could not recognize the configurations. Fortunately, I had backed up the archive previously, so I just had to copy it to the original folder, and everything was working again.

How to print a two dimensional array?

If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.

    int numDigits = (int) Math.log10(maxValue) + 1;
    if (numDigits <= 1) {
        numDigits = 2;
    }
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < matrix.length; i++) {
        int[] row = matrix[i];
        for (int j = 0; j < row.length; j++) {
            int block = row[j];
            buf.append(String.format("%" + numDigits + "d", block));
            if (j >= row.length - 1) {
                buf.append("\n");
            }
        }
    }
    return buf.toString();

Write a file in UTF-8 using FileWriter (Java)?

In my opinion

If you wanna write follow kind UTF-8.You should create a byte array.Then,you can do such as the following: byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();

Then, you can write each byte into file you created. Example:

OutputStream f=new FileOutputStream(xmlfile);
    byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();
    for (int i=0;i<by.length;i++){
    byte b=by[i];
    f.write(b);

    }
    f.close();

How to access a preexisting collection with Mongoose?

Are you sure you've connected to the db? (I ask because I don't see a port specified)

try:

mongoose.connection.on("open", function(){
  console.log("mongodb is connected!!");
});

Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?

From the look of your connection string, you should see the record in the "test" db.

Hope it helps!

Highcharts - how to have a chart with dynamic height?

Remove the height will fix your problem because highchart is responsive by design if you adjust your screen it will also re-size.

How to use @Nullable and @Nonnull annotations more effectively?

Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I had this problem and I couldn't find the solution here, so I want to share my solution in case someone else has this problem again.

I had this code:

public void finishAction() {
  onDestroy();
  finish();
}

and solved the problem by deleting the line "onDestroy();"

public void finishAction() {
  finish();
}

The reason I wrote the initial code: I know that when you execute "finish()" the activity calls "onDestroy()", but I'm using threads and I wanted to ensure that all the threads are destroyed before starting the next activity, and it looks like "finish()" is not always immediate. I need to process/reduce a lot of “Bitmap” and display big “bitmaps” and I’m working on improving the use of the memory in my app

Now I will kill the threads using a different method and I’ll execute this method from "onDestroy();" and when I think I need to kill all the threads.

public void finishAction() {
  onDestroyThreads();
  finish();
}

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

How do I convert array of Objects into one Object in JavaScript?

_x000D_
_x000D_
// original_x000D_
var arr = [{_x000D_
    key: '11',_x000D_
    value: '1100',_x000D_
    $$hashKey: '00X'_x000D_
  },_x000D_
  {_x000D_
    key: '22',_x000D_
    value: '2200',_x000D_
    $$hashKey: '018'_x000D_
  }_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
  obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

If you happen to use LuaSocket in your project, or just have it installed and don't mind to use it, you can use the socket.sleep(time) function which sleeps for a given amount of time (in seconds).

This works both on Windows and Unix, and you do not have to compile additional modules.

I should add that the function supports fractional seconds as a parameter, i.e. socket.sleep(0.5) will sleep half a second. It uses Sleep() on Windows and nanosleep() elsewhere, so you may have issues with Windows accuracy when time gets too low.

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

Linux find file names with given string recursively

A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.

man -k <your search term>

What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)

That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:

man -k find | egrep '\(1\)'

or, if you also want to look for commands that require higher privilege levels, like this:

man -k find | egrep '\([18]\)'

What is the purpose of the HTML "no-js" class?

This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.

<body class="no-js">
    <script>document.body.classList.remove('no-js');</script>
    ...
</body>

If javascript support is there, then it will remove no-js class. Otherwise no-js will remain in the body tag. Then they control the styles in the css when no javascript support.

.no-js .some-class-name {

}

How do I print debug messages in the Google Chrome JavaScript Console?

Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

(Or create your own console.log() which just returns false.)

Java - Convert image to Base64

new String(byteArray, 0, bytesRead); does not modify the array. You need to use System.arrayCopy to trim the array to the actual data size. Otherwise you are processing all 102400 bytes most of which are zeros.

Date query with ISODate in mongodb doesn't seem to work

Old question, but still first google hit, so i post it here so i find it again more easily...

Using Mongo 4.2 and an aggregate():

db.collection.aggregate(
    [
     { $match: { "end_time": { "$gt": ISODate("2020-01-01T00:00:00.000Z")  } } },
     { $project: {
          "end_day": { $dateFromParts: { 'year' : {$year:"$end_time"}, 'month' : {$month:"$end_time"}, 'day': {$dayOfMonth:"$end_time"}, 'hour' : 0  } }
     }}, 
     {$group:{
        _id:   "$end_day",
        "count":{$sum:1},
    }}
   ]
)

This one give you the groupby variable as a date, sometimes better to hande as the components itself.

How do I pass a list as a parameter in a stored procedure?

Check the below code this work for me

@ManifestNoList      VARCHAR(MAX)


WHERE
    (
        ManifestNo IN (SELECT value FROM dbo.SplitString(@ManifestNoList, ','))
    )

Simple way to count character occurrences in a string

public int countChar(String str, char c)
{
    int count = 0;

    for(int i=0; i < str.length(); i++)
    {    if(str.charAt(i) == c)
            count++;
    }

    return count;
}

This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

Get JSON object from URL

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);

//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];

Some time you might get 405, set the method type correctly.

MySQL DAYOFWEEK() - my week begins with monday

You can easily use the MODE argument:

MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions

If the mode argument is omitted, the value of the default_week_format system variable is used:

MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables

How to choose an AWS profile when using boto3 to connect to CloudFront

Do this to use a profile with name 'dev':

session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
    print(bucket.name)

What is a Sticky Broadcast?

The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Windows equivalent of the 'tail' command

No exact equivalent. However there exist a native DOS command "more" that has a +n option that will start outputting the file after the nth line:

DOS Prompt:

C:\>more +2 myfile.txt

The above command will output everything after the first 2 lines.
This is actually the inverse of Unix head:

Unix console:

root@server:~$ head -2 myfile.txt

The above command will print only the first 2 lines of the file.

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Unity Scripts edited in Visual studio don't provide autocomplete

I hit the same issues today using Visual Studio 2017 15.4.5 with Unity 2017.

I was able to fix the issue by right clicking on the project in Visual Studio and changing the target framework from 3.5 to 4.5.

Hope this helps anyone else in a similar scenario.

Get full path of the files in PowerShell

Try this:

Get-ChildItem C:\windows\System32 -Include *.txt -Recurse | select -ExpandProperty FullName

How to check if a symlink exists

Maybe this is what you are looking for. To check if a file exist and is not a link.

Try this command:

file="/usr/mda" 
[ -f $file ] && [ ! -L $file ] && echo "$file exists and is not a symlink"

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

C read file line by line

Implement method to read, and get content from a file (input1.txt)

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

void testGetFile() {
    // open file
    FILE *fp = fopen("input1.txt", "r");
    size_t len = 255;
    // need malloc memory for line, if not, segmentation fault error will occurred.
    char *line = malloc(sizeof(char) * len);
    // check if file exist (and you can open it) or not
    if (fp == NULL) {
        printf("can open file input1.txt!");
        return;
    }
    while(fgets(line, len, fp) != NULL) {
        printf("%s\n", line);
    }
    free(line);
}

Hope this help. Happy coding!

How To Get Selected Value From UIPickerView

You can get it in the following manner:

NSInteger row;
NSArray *repeatPickerData;
UIPickerView *repeatPickerView;

row = [repeatPickerView selectedRowInComponent:0];
self.strPrintRepeat = [repeatPickerData objectAtIndex:row];

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

How do you perform address validation?

As mentioned there are many services out there, if you are looking to truly validate the entire address then I highly recommend going with a Web Service type service to ensure that changes can quickly be recognized by your application.

In addition to the services listed above, webservice.net has this US Address Validation service. http://www.webservicex.net/WCF/ServiceDetails.aspx?SID=24

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

How to detect a remote side socket close?

The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.

How to get the current time in Python

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

How does Java import work?

Java's import statement is pure syntactical sugar. import is only evaluated at compile time to indicate to the compiler where to find the names in the code.

You may live without any import statement when you always specify the full qualified name of classes. Like this line needs no import statement at all:

javax.swing.JButton but = new  javax.swing.JButton();

The import statement will make your code more readable like this:

import javax.swing.*;

JButton but = new JButton();

How to disable SSL certificate checking with Spring RestTemplate?

In my case, with letsencrypt https, this was caused by using cert.pem instead of fullchain.pem as the certificate file on the requested server. See this thread for details.

What is the meaning of # in URL and how can I use that?

Originally it was used as an anchor to jump to an element with the same name/id.

However, nowadays it's usually used with AJAX-based pages since changing the hash can be detected using JavaScript and allows you to use the back/forward button without actually triggering a full page reload.

Update statement with inner join on Oracle

Using description instead of desc for table2,

update
  table1
set
  value = (select code from table2 where description = table1.value)
where
  exists (select 1 from table2 where description = table1.value)
  and
  table1.updatetype = 'blah'
;

How to make div appear in front of another?

The black div will display the full 500px unless overflow:hidden is set on the 100px li

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a javascript library for this, see FileSaver.js on Github

However the saveAs() function won't send pure string to the browser, you need to convert it to blob:

function data2blob(data, isBase64) {
  var chars = "";

  if (isBase64)
    chars = atob(data);
  else
    chars = data;

  var bytes = new Array(chars.length);
  for (var i = 0; i < chars.length; i++) {
    bytes[i] = chars.charCodeAt(i);
  }

  var blob = new Blob([new Uint8Array(bytes)]);
  return blob;
}

and then call saveAs on the blob, as like:

var myString = "my string with some stuff";
saveAs( data2blob(myString), "myString.txt" );

Of course remember to include the above-mentioned javascript library on your webpage using <script src=FileSaver.js>

What is the !! (not not) operator in JavaScript?

! is "boolean not", which essentially typecasts the value of "enable" to its boolean opposite. The second ! flips this value. So, !!enable means "not not enable," giving you the value of enable as a boolean.

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

Python function to convert seconds into minutes, hours, and days

def normalize_seconds(seconds: int) -> tuple:
    (days, remainder) = divmod(seconds, 86400)
    (hours, remainder) = divmod(remainder, 3600)
    (minutes, seconds) = divmod(remainder, 60)

    return namedtuple("_", ("days", "hours", "minutes", "seconds"))(days, hours, minutes, seconds)

How to set up a PostgreSQL database in Django

You need to install psycopg2 Python library.

Installation


Download http://initd.org/psycopg/, then install it under Python PATH

After downloading, easily extract the tarball and:

$ python setup.py install

Or if you wish, install it by either easy_install or pip.

(I prefer to use pip over easy_install for no reason.)

  • $ easy_install psycopg2
  • $ pip install psycopg2

Configuration


in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

- Other installation instructions can be found at download page and install page.

Sorting a Dictionary in place with respect to keys

The correct answer is already stated (just use SortedDictionary).

However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...

Dictionary<string, int> dupcheck = new Dictionary<string, int>();

...some code that fills in "dupcheck", then...

if (dupcheck.Count > 0) {
  Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
  var keys_sorted = dupcheck.Keys.ToList();
    keys_sorted.Sort();
  foreach (var k in keys_sorted) {
    Console.WriteLine("{0} = {1}", k, dupcheck[k]);
  }
}

Don't forget using System.Linq; for this.

With block equivalent in C#?

Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.

(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)

How to set the font style to bold, italic and underlined in an Android TextView?

For bold and italic whatever you are doing is correct for underscore use following code

HelloAndroid.java

 package com.example.helloandroid;

 import android.app.Activity;
 import android.os.Bundle;
 import android.text.SpannableString;
 import android.text.style.UnderlineSpan;
import android.widget.TextView;

public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textview = (TextView)findViewById(R.id.textview);
    SpannableString content = new SpannableString(getText(R.string.hello));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textview.setText(content);
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
android:textStyle="bold|italic"/>

string.xml

<?xml version="1.0" encoding="utf-8"?>
 <resources>
  <string name="hello">Hello World, HelloAndroid!</string>
  <string name="app_name">Hello, Android</string>
</resources>

Can you split a stream into two streams?

This was the least bad answer I could come up with.

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

public class Test {

    public static <T, L, R> Pair<L, R> splitStream(Stream<T> inputStream, Predicate<T> predicate,
            Function<Stream<T>, L> trueStreamProcessor, Function<Stream<T>, R> falseStreamProcessor) {

        Map<Boolean, List<T>> partitioned = inputStream.collect(Collectors.partitioningBy(predicate));
        L trueResult = trueStreamProcessor.apply(partitioned.get(Boolean.TRUE).stream());
        R falseResult = falseStreamProcessor.apply(partitioned.get(Boolean.FALSE).stream());

        return new ImmutablePair<L, R>(trueResult, falseResult);
    }

    public static void main(String[] args) {

        Stream<Integer> stream = Stream.iterate(0, n -> n + 1).limit(10);

        Pair<List<Integer>, String> results = splitStream(stream,
                n -> n > 5,
                s -> s.filter(n -> n % 2 == 0).collect(Collectors.toList()),
                s -> s.map(n -> n.toString()).collect(Collectors.joining("|")));

        System.out.println(results);
    }

}

This takes a stream of integers and splits them at 5. For those greater than 5 it filters only even numbers and puts them in a list. For the rest it joins them with |.

outputs:

 ([6, 8],0|1|2|3|4|5)

Its not ideal as it collects everything into intermediary collections breaking the stream (and has too many arguments!)

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

Perl - Multiple condition if statement without duplicating code?

I don't recommend storing passwords in a script, but this is a way to what you indicate:

use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );

say ( $user_table{ $name } eq $password ? 'You have gained access.'
    :                                     'Access denied!'
    );

Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

BackgroundTint works as color filter.

FEFBDE as tint

37AEE4 as background

Try seeing the difference by comment tint/background and check the output when both are set.

How do I concatenate two lists in Python?

For cases with a low number of lists you can simply add the lists together or use in-place unpacking (available in Python-3.5+):

In [1]: listone = [1, 2, 3] 
   ...: listtwo = [4, 5, 6]                                                                                                                                                                                 

In [2]: listone + listtwo                                                                                                                                                                                   
Out[2]: [1, 2, 3, 4, 5, 6]
                                                                                                                                                                                     
In [3]: [*listone, *listtwo]                                                                                                                                                                                
Out[3]: [1, 2, 3, 4, 5, 6]

As a more general way for cases with more number of lists, as a pythonic approach, you can use chain.from_iterable()1 function from itertoold module. Also, based on this answer this function is the best; or at least a very food way for flatting a nested list as well.

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1. Note that `chain.from_iterable()` is available in Python 2.6 and later. In other versions, use `chain(*l)`.

jQuery when element becomes visible

Tried this on firefox, works http://jsfiddle.net/Tm26Q/1/

$(function(){
 /** Just to mimic a blinking box on the page**/
  setInterval(function(){$("div#box").hide();},2001);
  setInterval(function(){$("div#box").show();},1000);
 /**/
});

$("div#box").on("DOMAttrModified",
function(){if($(this).is(":visible"))console.log("visible");});

UPDATE

Currently the Mutation Events (like DOMAttrModified used in the solution) are replaced by MutationObserver, You can use that to detect DOM node changes like in the above case.

Concept behind putting wait(),notify() methods in Object class

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html

"No cached version... available for offline mode."

In my case I get the same error title could not resolve all dependencies for configuration

However suberror said, it was due to a linting jar not loaded with its url given saying status 502 received, I ran the deployment command again, this time it succeeded.

How to read a single char from the console in Java (as the user types it)?

I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.

  • On Windows it uses _kbhit() and _getwch() from msvcrt.dll.
  • On Unix it uses tcsetattr() to switch the console to non-canonical mode, System.in.available() to check whether data is available and System.in.read() to read bytes from the console. A CharsetDecoder is used to convert bytes to characters.

It supports non-blocking input and mixing raw mode and normal line mode input.

Listing only directories in UNIX

The following

find * -maxdepth 0 -type d

basically filters the expansion of '*', i.e. all entries in the current dir, by the -type d condition.

Advantage is that, output is same as ls -1 *, but only with directories and entries do not start with a dot

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

Undefined symbols for architecture x86_64 on Xcode 6.1

Same error when I copied/pasted a class and forgot to rename it in .m file.

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

When to use std::size_t?

size_t is unsigned int. so whenever you want unsigned int you can use it.

I use it when i want to specify size of the array , counter ect...

void * operator new (size_t size); is a good use of it.

Difference between arguments and parameters in Java

Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.

You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments

How to get the wsdl file from a webservice's URL

By postfixing the URL with ?WSDL

If the URL is for example:

http://webservice.example:1234/foo

You use:

http://webservice.example:1234/foo?WSDL

And the wsdl will be delivered.

Confused by python file mode "w+"

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Find out a Git branch creator

You can find out who created a branch in your local repository by

git reflog --format=full

Example output:

commit e1dd940
Reflog: HEAD@{0} (a <a@none>)
Reflog message: checkout: moving from master to b2
Author: b <b.none>
Commit: b <b.none>
(...)

But this is probably useless as typically on your local repository only you create branches.

The information is stored at ./.git/logs/refs/heads/branch. Example content:

0000000000000000000000000000000000000000 e1dd9409c4ba60c28ad9e7e8a4b4c5ed783ba69b a <a@none> 1438788420 +0200   branch: Created from HEAD

The last commit in this example was from user "b" while the branch "b2" was created by user "a". If you change your username you can verify that git reflog takes the information from the log and does not use the local user.

I don't know about any possibility to transmit that local log information to a central repository.

How to draw a rounded Rectangle on HTML Canvas?

Juan, I made a slight improvement to your method to allow for changing each rectangle corner radius individually:

/** 
 * Draws a rounded rectangle using the current state of the canvas.  
 * If you omit the last three params, it will draw a rectangle  
 * outline with a 5 pixel border radius  
 * @param {Number} x The top left x coordinate 
 * @param {Number} y The top left y coordinate  
 * @param {Number} width The width of the rectangle  
 * @param {Number} height The height of the rectangle 
 * @param {Object} radius All corner radii. Defaults to 0,0,0,0; 
 * @param {Boolean} fill Whether to fill the rectangle. Defaults to false. 
 * @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true. 
 */
CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius, fill, stroke) {
    var cornerRadius = { upperLeft: 0, upperRight: 0, lowerLeft: 0, lowerRight: 0 };
    if (typeof stroke == "undefined") {
        stroke = true;
    }
    if (typeof radius === "object") {
        for (var side in radius) {
            cornerRadius[side] = radius[side];
        }
    }

    this.beginPath();
    this.moveTo(x + cornerRadius.upperLeft, y);
    this.lineTo(x + width - cornerRadius.upperRight, y);
    this.quadraticCurveTo(x + width, y, x + width, y + cornerRadius.upperRight);
    this.lineTo(x + width, y + height - cornerRadius.lowerRight);
    this.quadraticCurveTo(x + width, y + height, x + width - cornerRadius.lowerRight, y + height);
    this.lineTo(x + cornerRadius.lowerLeft, y + height);
    this.quadraticCurveTo(x, y + height, x, y + height - cornerRadius.lowerLeft);
    this.lineTo(x, y + cornerRadius.upperLeft);
    this.quadraticCurveTo(x, y, x + cornerRadius.upperLeft, y);
    this.closePath();
    if (stroke) {
        this.stroke();
    }
    if (fill) {
        this.fill();
    }
} 

Use it like this:

var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
c.fillStyle = "blue";
c.roundRect(50, 100, 50, 100, {upperLeft:10,upperRight:10}, true, true);

Git: list only "untracked" files (also, custom commands)

If you just want to remove untracked files, do this:

git clean -df

add x to that if you want to also include specifically ignored files. I use git clean -dfx a lot throughout the day.

You can create custom git by just writing a script called git-whatever and having it in your path.

How do I start a process from C#?

As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...

using System.Diagnostics;
...
Process.Start("process.exe");

The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

This method allows far more control than I've mentioned.

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

Git command to display HEAD commit id?

git rev-parse --abbrev-ref HEAD

What's the fastest way of checking if a point is inside a polygon in python

You can consider shapely:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))

From the methods you've mentioned I've only used the second, path.contains_points, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):

from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np

first = -3
size  = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags

xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()

, the results is this:

point inside polygon within pixel tolerance

Change the color of a checked menu item in a navigation drawer

Here is the another way to achive this:

public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            item.setEnabled(true);
            item.setTitle(Html.fromHtml("<font color='#ff3824'>Settings</font>"));
            return false;
            }
        });


    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Why do we need C Unions?

It's difficult to think of a specific occasion when you'd need this type of flexible structure, perhaps in a message protocol where you would be sending different sizes of messages, but even then there are probably better and more programmer friendly alternatives.

Unions are a bit like variant types in other languages - they can only hold one thing at a time, but that thing could be an int, a float etc. depending on how you declare it.

For example:

typedef union MyUnion MYUNION;
union MyUnion
{
   int MyInt;
   float MyFloat;
};

MyUnion will only contain an int OR a float, depending on which you most recently set. So doing this:

MYUNION u;
u.MyInt = 10;

u now holds an int equal to 10;

u.MyFloat = 1.0;

u now holds a float equal to 1.0. It no longer holds an int. Obviously now if you try and do printf("MyInt=%d", u.MyInt); then you're probably going to get an error, though I'm unsure of the specific behaviour.

The size of the union is dictated by the size of its largest field, in this case the float.

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

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

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

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

How to upload a file and JSON data in Postman?

Use below code in spring rest side :

@PostMapping(value = Constant.API_INITIAL + "/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file,String jsonFileVo) {
        FileUploadVo fileUploadVo = null;
        try {
            fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

enter image description here

trying to align html button at the center of the my page

For me it worked using flexbox.

Add a css class around the parent div / element with :

.parent {
    display: flex;
}

and for the button use:

.button {
    justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If your C/C++ code is portable to *nix, few things are better than Valgrind.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

Wow, this one took me a while to solve, as I was using SVN through Eclipse. In the end, the only thing that worked for me was to commit all non-affected files, then (with Eclipse closed) rename the project directory, and re-check the project out from SVN. Glad it works properly now!

Styling JQuery UI Autocomplete

Bootstrap styling for jQuery UI Autocomplete

    .ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
}

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
}

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
}

What does principal end of an association means in 1:1 relationship in Entity framework

You can also use the [Required] data annotation attribute to solve this:

public class Foo
{
    public string FooId { get; set; }

    public Boo Boo { get; set; }
}

public class Boo
{
    public string BooId { get; set; }

    [Required]
    public Foo Foo {get; set; }
}

Foo is required for Boo.

Is it possible to cast a Stream in Java 8?

Along the lines of ggovan's answer, I do this as follows:

/**
 * Provides various high-order functions.
 */
public final class F {
    /**
     * When the returned {@code Function} is passed as an argument to
     * {@link Stream#flatMap}, the result is a stream of instances of
     * {@code cls}.
     */
    public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
        return o -> cls.isInstance(o)
                ? Stream.of(cls.cast(o))
                : Stream.empty();
    }
}

Using this helper function:

Stream.of(objects).flatMap(F.instancesOf(Client.class))
        .map(Client::getId)
        .forEach(System.out::println);

Disable future dates in jQuery UI Datepicker

Code for Future Date only with disable today's date.

 var d = new Date();
         $("#delivdate").datepicker({
         showOn: "button",
         buttonImage: base_url+"images/cal.png",
         minDate:new Date(d.setDate(d.getDate() + 1)),
         buttonImageOnly: true
        });
         $('.ui-datepicker-trigger').attr('title',''); 

Wait until boolean value changes it state

I prefer to use mutex mechanism in such cases, but if you really want to use boolean, then you should declare it as volatile (to provide the change visibility across threads) and just run the body-less cycle with that boolean as a condition :

//.....some class

volatile boolean someBoolean; 

Thread someThread = new Thread() {

    @Override 
    public void run() {
        //some actions
        while (!someBoolean); //wait for condition 
        //some actions 
    }

};

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

DataTables fixed headers misaligned with columns in wide tables

I have fixed the column issue bu using below concept

$(".panel-title a").click(function(){
    setTimeout( function(){
           $('#tblSValidationFilerGrid').DataTable().search( '' ).draw();
        }, 10 );
})

Combine two (or more) PDF's

I used iTextsharp with c# to combine pdf files. This is the code I used.

string[] lstFiles=new string[3];
    lstFiles[0]=@"C:/pdf/1.pdf";
    lstFiles[1]=@"C:/pdf/2.pdf";
    lstFiles[2]=@"C:/pdf/3.pdf";

    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage;
    string outputPdfPath=@"C:/pdf/new.pdf";


    sourceDocument = new Document();
    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

    //Open the output file
    sourceDocument.Open();

    try
    {
        //Loop through the files list
        for (int f = 0; f < lstFiles.Length-1; f++)
        {
            int pages =get_pageCcount(lstFiles[f]);

            reader = new PdfReader(lstFiles[f]);
            //Add pages of current file
            for (int i = 1; i <= pages; i++)
            {
                importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                pdfCopyProvider.AddPage(importedPage);
            }

            reader.Close();
         }
        //At the end save the output file
        sourceDocument.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }


private int get_pageCcount(string file)
{
    using (StreamReader sr = new StreamReader(File.OpenRead(file)))
    {
        Regex regex = new Regex(@"/Type\s*/Page[^s]");
        MatchCollection matches = regex.Matches(sr.ReadToEnd());

        return matches.Count;
    }
}

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

How to import a jar in Eclipse

You can add a jar in Eclipse by right-clicking on the Project ? Build Path ? Configure Build Path. Under Libraries tab, click Add Jars or Add External JARs and give the Jar. A quick demo here.

enter image description here

The above solution is obviously a "Quick" one. However, if you are working on a project where you need to commit files to the source control repository, I would recommend adding Jar files to a dedicated library folder within your source control repository and referencing few or all of them as mentioned above.

Convert special characters to HTML in Javascript

This doesn't direcly answer your question, but if you are using innerHTML in order to write text within an element and you ran into encoding issues, just use textContent, i.e.:

var s = "Foo 'bar' baz <qux>";

var element = document.getElementById('foo');
element.textContent = s;

// <div id="foo">Foo 'bar' baz <qux></div>

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

JUNIT testing void methods

If it is possible in your case, you could make your methods method1(arg1) ... method7() protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.

Moving items around in an ArrayList

Kotlin solution to move an Element from "fromPos" to "toPos" and shift all other items accordingly (useful for moving an item in a staggered layout recyclerView in an Android application)

            if(fromPos < toPos){                    
                val movingElement = myList[fromPos]
                //shifts all elements between fromPos and toPos 1 down
                for(i in fromPos+1..toPos){
                    myList[i-1] = myList[i]
                }
                //re-add element that was saved in the beginning
                myList[toPos] = movingElement
            }

            if(fromPos > toPos){
                val movingElement = myList[fromPos]
                //shifts elements between toPos and fromPos 1 up
                for(i in fromPos downTo toPos+1){
                    myList[i] = myList[i-1]
                }                    
                //re-add element that was saved in the beginning
                myList[toPos] = movingElement
            }

Create an instance of a class from a string

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

Add new row to excel Table (VBA)

Ran into this issue today (Excel crashes on adding rows using .ListRows.Add). After reading this post and checking my table, I realized the calculations of the formula's in some of the cells in the row depend on a value in other cells. In my case of cells in a higher column AND even cells with a formula!

The solution was to fill the new added row from back to front, so calculations would not go wrong.

Excel normally can deal with formula's in different cells, but it seems adding a row in a table kicks of a recalculation in order of the columns (A,B,C,etc..).

Hope this helps clearing issues with .ListRows.Add

Multiple REPLACE function in Oracle

The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

If you are going to make heavy use of this, you could consider writing your own function:

CREATE TYPE t_text IS TABLE OF VARCHAR2(256);

CREATE FUNCTION multiple_replace(
  in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
  RETURN VARCHAR2
AS
  v_result VARCHAR2(32767);
BEGIN
  IF( in_old.COUNT <> in_new.COUNT ) THEN
    RETURN in_text;
  END IF;
  v_result := in_text;
  FOR i IN 1 .. in_old.COUNT LOOP
    v_result := REPLACE( v_result, in_old(i), in_new(i) );
  END LOOP;
  RETURN v_result;
END;

and then use it like this:

SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                         NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                         NEW t_text( 'text', 'tokens', 'replace' )
                       )
FROM dual

This is text with some tokens to replace

If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

How to take last four characters from a varchar?

SUBSTR(column, LENGTH(column) - 3, 4)

LENGTH returns length of string and SUBSTR returns 4 characters from "the position length - 4"

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

How to get all options of a select using jQuery?

    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);

How do I get the path of a process in Unix / Linux

You can also get the path on GNU/Linux with (not thoroughly tested):

char file[32];
char buf[64];
pid_t pid = getpid();
sprintf(file, "/proc/%i/cmdline", pid);
FILE *f = fopen(file, "r");
fgets(buf, 64, f);
fclose(f);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

*strrchr(buf, '/') = '\0';
/*chdir(buf);*/

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

This is a very interesting question! As a float requires some bits to store the exponent (=bits_for_exponent) any floating point number greater than 2**(float_size - bits_for_exponent) will always be an integral value! At the other extreme a float with a negative exponent will give one of 1, 0 or -1. This makes the discussion of integer range versus float range moot because these functions will simply return the original number whenever the number is outside the range of the integer type. The python functions are wrappers of the C function and so this is really a deficiency of the C functions where they should have returned an integer and forced the programer to do the range/NaN/Inf check before calling ceil/floor.

Thus the logical answer is the only time these functions are useful they would return a value within integer range and so the fact they return a float is a mistake and you are very smart for realizing this!

How can I send an HTTP POST request to a server from Excel using VBA?

To complete the response of the other users:

For this I have created an "WinHttp.WinHttpRequest.5.1" object.

Send a post request with some data from Excel using VBA:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

Send a get request with token authentication from Excel using VBA:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send

Controlling mouse with Python

As of 2021, you can use mouse:

import mouse
mouse.move("500", "500")
mouse.left_click()

Features

  • Global event hook on all mice devices (captures events regardless of focus).
  • Listen and sends mouse events.
  • Works with Windows and Linux (requires sudo).
  • Pure Python, no C modules to be compiled.
  • Zero dependencies. Trivial to install and deploy, just copy the files.
  • Python 2 and 3
  • Includes high level API (e.g. record and play).
  • Events automatically captured in separate thread, doesn't block main program.
  • Tested and documented.

What's the idiomatic syntax for prepending to a short python list?

Lets go over 4 methods

  1. Using insert()
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using [] and +
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using Slicing
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using collections.deque.appendleft()
>>> 
>>> from collections import deque
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 

good example of Javadoc

I use a small set of documentation patterns:

  • always documenting about thread-safety
  • always documenting immutability
  • javadoc with examples (like Formatter)
  • @Deprecation with WHY and HOW to replace the annotated element

Is there an R function for finding the index of an element in a vector?

the function Position in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.

Position(f, x, right = FALSE, nomatch = NA_integer)

How to remove gem from Ruby on Rails application?

You can use

gem uninstall <gem-name>

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

Check if object value exists within a Javascript array of objects and if not add a new object to array

This is what I did in addition to @sagar-gavhane's answer

const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]

const userExists = users.some(user => user.name === newUser.name);
if(userExists) {
    return new Error({error:'User exists'})
}
users.push(newUser)

How to detect page zoom level in all modern browsers?

Your calculations are still based on a number of CSS pixels. They're just a different size on the screen now. That's the point of full page zoom.

What would you want to happen on a browser on a 192dpi device which therefore normally displayed four device pixels for each pixel in an image? At 50% zoom this device now displays one image pixel in one device pixel.

How to retrieve records for last 30 minutes in MS SQL?

DATEADD only returned Function does not exist on MySQL 5.5.53 (I know it's old)

Instead, I found DatePlayed > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 30 minute) to produce the desired result

How create a new deep copy (clone) of a List<T>?

If the Array class meets your needs, you could also use the List.ToArray method, which copies elements to a new array.

Reference: http://msdn.microsoft.com/en-us/library/x303t819(v=vs.110).aspx

Shortcuts in Objective-C to concatenate NSStrings

How about shortening stringByAppendingString and use a #define:

#define and stringByAppendingString

Thus you would use:

NSString* myString = [@"Hello " and @"world"];

Problem is that it only works for two strings, you're required to wrap additional brackets for more appends:

NSString* myString = [[@"Hello" and: @" world"] and: @" again"];

How to run a .awk file?

The file you give is a shell script, not an awk program. So, try sh my.awk.

If you want to use awk -f my.awk life.csv > life_out.cs, then remove awk -F , ' and the last line from the file and add FS="," in BEGIN.

Sum of values in an array using jQuery

You don't need jQuery. You can do this using a for loop:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

Wait 5 seconds before executing next line

You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.

For example:

function stateChange(newState) {
    setTimeout(function(){
        if(newState == -1){alert('VIDEO HAS STOPPED');}
    }, 5000);
}

But, if you have code like this:

stateChange(-1);
console.log("Hello");

The console.log() statement will run immediately. It will not wait until after the timeout fires in the stateChange() function. You cannot just pause javascript execution for a predetermined amount of time.

Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function).

If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.

Rails: Can't verify CSRF token authenticity when making a POST request

Since Rails 5 you can also create a new class with ::API instead of ::Base:

class ApiController < ActionController::API
end

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No, it won't wait.

You could use performSelectorOnMainThread:withObject:waitUntilDone:.

Angular2 change detection: ngOnChanges not firing for nested object

I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject.

If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects.

As already said, use of changeDetectionStrategy.onPush

Say you have this component you made, with changeDetectionStrategy.onPush:

<component [collection]="myCollection"></component>

Then you'd push an item and trigger the change detection :

myCollection.push(anItem);
refresh();

or you'd remove an item and trigger the change detection :

myCollection.splice(0,1);
refresh();

or you'd change an attrbibute value for an item and trigger the change detection :

myCollection[5].attribute = 'new value';
refresh();

Content of refresh :

refresh() : void {
    this.myCollection = this.myCollection.slice();
}

The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :)

Regards,

How is a non-breaking space represented in a JavaScript string?

&nbsp; is a HTML entity. When doing .text(), all HTML entities are decoded to their character values.

Instead of comparing using the entity, compare using the actual raw character:

var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
  x = '';
}

Or you can also create the character from the character code manually it in its Javascript escaped form:

var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
  x = '';
}

More information about String.fromCharCode is available here:

fromCharCode - MDC Doc Center

More information about character codes for different charsets are available here:

Windows-1252 Charset
UTF-8 Charset

How do I get the latest version of my code?

If the above commands didn't help you use this method:

  1. Go to the git archive where you have Fork
  2. Click Settings> Scroll down and click Delete this repository
  3. Confirm delete
  4. Fork again, and re-enter the git clone <url_git>
  5. You already have the latest version

Working with $scope.$emit and $scope.$on

You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.

app.controller('firstCtrl', function($scope, $rootScope) {        
        function firstCtrl($scope) {
        {
            $rootScope.$emit('someEvent', [1,2,3]);
        }
}

app.controller('secondCtrl', function($scope, $rootScope) {
        function secondCtrl($scope)
        {
            $rootScope.$on('someEvent', function(event, data) { console.log(data); });
        }
}

Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.

Margin while printing html page

Updated, Simple Solution

@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}



div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

The following works perfectly:-

if(isset($_POST['signup'])){
$username=mysqli_real_escape_string($connect,$_POST['username']);
$email=mysqli_real_escape_string($connect,$_POST['email']);
$pass1=mysqli_real_escape_string($connect,$_POST['pass1']);
$pass2=mysqli_real_escape_string($connect,$_POST['pass2']);

Now, the $connect is my variable containing my connection to the database. You only left out the connection variable. Include it and it shall work perfectly.

What is the most efficient way to check if a value exists in a NumPy array?

Fascinating. I needed to improve the speed of a series of loops that must perform matching index determination in this same way. So I decided to time all the solutions here, along with some riff's.

Here are my speed tests for Python 2.7.10:

import timeit
timeit.timeit('N.any(N.in1d(sids, val))', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

18.86137104034424

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = [20010401010101+x for x in range(1000)]')

15.061666011810303

timeit.timeit('N.in1d(sids, val)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

11.613027095794678

timeit.timeit('N.any(val == sids)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

7.670552015304565

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

5.610057830810547

timeit.timeit('val == sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

1.6632978916168213

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = set([20010401010101+x for x in range(1000)])')

0.0548710823059082

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = dict(zip([20010401010101+x for x in range(1000)],[True,]*1000))')

0.054754018783569336

Very surprising! Orders of magnitude difference!

To summarize, if you just want to know whether something's in a 1D list or not:

  • 19s N.any(N.in1d(numpy array))
  • 15s x in (list)
  • 8s N.any(x == numpy array)
  • 6s x in (numpy array)
  • .1s x in (set or a dictionary)

If you want to know where something is in the list as well (order is important):

  • 12s N.in1d(x, numpy array)
  • 2s x == (numpy array)

Read file-contents into a string in C++

maybe not the most efficient, but reads data in one line:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}

Understanding unique keys for array children in React.js

I had a unique key, just had to pass it as a prop like this:

<CompName key={msg._id} message={msg} />

This page was helpful:

https://reactjs.org/docs/lists-and-keys.html#keys

Default value to a parameter while passing by reference in C++

It's possible with const qualifier for State:

virtual const ULONG Write(const ULONG &State = 0, bool sequence = true);

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

Disable browser 'Save Password' functionality

Since most of the autocomplete suggestions, including the accepted answer, don't work in today's web browsers (i.e. web browser password managers ignore autocomplete), a more novel solution is to swap between password and text types and make the background color match the text color when the field is a plain text field, which continues to hide the password while being a real password field when the user (or a program like KeePass) is entering a password. Browsers don't ask to save passwords that are stored in plain text fields.

The advantage of this approach is that it allows for progressive enhancement and therefore doesn't require Javascript for a field to function as a normal password field (you could also start with a plain text field instead and apply the same approach but that's not really HIPAA PHI/PII-compliant). Nor does this approach depend on hidden forms/fields which might not necessarily be sent to the server (because they are hidden) and some of those tricks also don't work either in several modern browsers.

jQuery plugin:

https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js

Relevant source code from the above link:

(function($) {
$.fn.StopPasswordManager = function() {
    return this.each(function() {
        var $this = $(this);

        $this.addClass('no-print');
        $this.attr('data-background-color', $this.css('background-color'));
        $this.css('background-color', $this.css('color'));
        $this.attr('type', 'text');
        $this.attr('autocomplete', 'off');

        $this.focus(function() {
            $this.attr('type', 'password');
            $this.css('background-color', $this.attr('data-background-color'));
        });

        $this.blur(function() {
            $this.css('background-color', $this.css('color'));
            $this.attr('type', 'text');
            $this[0].selectionStart = $this[0].selectionEnd;
        });

        $this.on('keydown', function(e) {
            if (e.keyCode == 13)
            {
                $this.css('background-color', $this.css('color'));
                $this.attr('type', 'text');
                $this[0].selectionStart = $this[0].selectionEnd;
            }
        });
    });
}
}(jQuery));

Demo:

https://barebonescms.com/demos/admin_pack/admin.php

Click "Add Entry" in the menu and then scroll to the bottom of the page to "Module: Stop Password Manager".

Disclaimer: While this approach works for sighted individuals, there might be issues with screen reader software. For example, a screen reader might read the user's password out loud because it sees a plain text field. There might also be other unforeseen consequences of using the above plugin. Altering built-in web browser functionality should be done sparingly with testing a wide variety of conditions and edge cases.

powershell mouse move does not prevent idle mode

I've added a notification that you can easily enable / disable just setting its variable to $true or $false. Also the mouse cursor moves 1 px right and then 1 px left so it basically stays in the same place even after several iterations.

# Lines needed for the notification
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms 
$isNotificationOn = $true

$secondsBetweenMouseMoves = 6
$Pos = [System.Windows.Forms.Cursor]::Position
$PosDelta = 1
$logFilename = "previousMouseMoverAction.txt"
$errorLogFilename = "mouseMoverLog.txt"

if (!(Test-Path "$PSScriptRoot\$logFilename")) {
   New-Item -path $PSScriptRoot -name $logFilename -type "file" -value "right"
   Write-Host "Warning: previousMouseMoverAction.txt missing, created a new one."
}

$previousPositionChangeAction = Get-Content -Path $PSScriptRoot\$logFilename

if ($previousPositionChangeAction -eq "left") {
    $PosDelta = 1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'right'
} else {
    $PosDelta = -1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'left'
}

for ($i = 0; $i -lt $secondsBetweenMouseMoves; $i++) {
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + $PosDelta) , $Pos.Y)
    if ($isNotificationOn) {
        # Sending a notification to the user
        $global:balloon = New-Object System.Windows.Forms.NotifyIcon
        $path = (Get-Process -id $pid).Path
        $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) 
        $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning 
        $balloon.BalloonTipText = 'I have just moved your cheese...'
        $balloon.BalloonTipTitle = "Attention, $Env:USERNAME" 
        $balloon.Visible = $true 
        $balloon.ShowBalloonTip(3000)
    }
}

How to add image background to btn-default twitter-bootstrap button?

This works with font awesome:

<button class="btn btn-outline-success">
   <i class="fa fa-print" aria-hidden="true"></i>
   Print
</button>

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Call a PHP function after onClick HTML event

<div id="sample"></div>   
 <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>

<script>

    $(document).ready(function(){
         $("#submitButton").click(function(){
            $("#sample").load(filenameofyourfunction?the the variable you need);
         });
    });

</script>

Assign output of a program to a variable using a MS batch file

As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:

    for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i

remove white space from the end of line in linux

If your lines are exactly the way you depict them(no leading or embedded spaces), the following should serve as well

awk '{$1=$1;print}' file.txt

How are "mvn clean package" and "mvn clean install" different?

Well, both will clean. That means they'll remove the target folder. The real question is what's the difference between package and install?

package will compile your code and also package it. For example, if your pom says the project is a jar, it will create a jar for you when you package it and put it somewhere in the target directory (by default).

install will compile and package, but it will also put the package in your local repository. This will make it so other projects can refer to it and grab it from your local repository.

Documentation

Import Certificate to Trusted Root but not to Personal [Command Line]

To print the content of Root store:

certutil -store Root

To output content to a file:

certutil -store Root > root_content.txt

To add certificate to Root store:

certutil -addstore -enterprise Root file.cer

Getting the thread ID from a thread

The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):

public static int GetNativeThreadId(Thread thread)
{
    var f = typeof(Thread).GetField("DONT_USE_InternalThread",
        BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

    var pInternalThread = (IntPtr)f.GetValue(thread);
    var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
    return nativeId;
}

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

Git: How to remove proxy

If you already unset the proxy from global and local level and still see the proxy details while you do

         git config -l

then unset the variable from system level, generally the configuration stored at below location

 C:\Program Files\Git\mingw64/etc/gitconfig

How to add an object to an array

Expanding Gabi Purcaru's answer to include an answer to number 2.

a = new Array();
b = new Object();
a[0] = b;

var c = a[0]; // c is now the object we inserted into a...

How to get mouse position in jQuery without mouse-events?

I don't believe there's a way to query the mouse position, but you can use a mousemove handler that just stores the information away, so you can query the stored information.

jQuery(function($) {
    var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
    });

    // ELSEWHERE, your code that needs to know the mouse position without an event
    if (currentMousePos.x < 10) {
        // ....
    }
});

But almost all code, other than setTimeout code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...

Create a custom event in Java

What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer and java.util.Observable

Escape a string for a sed replace pattern

The sed command allows you to use other characters instead of / as separator:

sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'

The double quotes are not a problem.

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

Handling errors in Promise.all

As @jib said,

Promise.all is all or nothing.

Though, you can control certain promises that are "allowed" to fail and we would like to proceed to .then.

For example.

  Promise.all([
    doMustAsyncTask1,
    doMustAsyncTask2,
    doOptionalAsyncTask
    .catch(err => {
      if( /* err non-critical */) {
        return
      }
      // if critical then fail
      throw err
    })
  ])
  .then(([ mustRes1, mustRes2, optionalRes ]) => {
    // proceed to work with results
  })

php var_dump() vs print_r()

With large arrays, print_r can show far more information than is useful. You can truncate it like this, showing the first 2000 characters or however many you need.

  echo "<pre>" . substr(print_r($dataset, 1), 0, 2000) . "</pre>";

<script> tag vs <script type = 'text/javascript'> tag

You only need <script></script> Tag that's it. <script type="text/javascript"></script> is not a valid HTML tag, so for best SEO practice use <script></script>

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

Excel Reference To Current Cell

Inside tables you can use [@] which (unfortunately) Excel automatically expands to Table1[@] but it does work. (I'm using Excel 2010)

For example when having two columns [Change] and [Balance], putting this in the [Balance] column:

=OFFSET([@], -1, 0) + [Change]

Note of course that this depends on the order of the rows (just like most any other solution), so it's a bit fragile.

how to resolve DTS_E_OLEDBERROR. in ssis

I had a similar issue with my OLE DB Command and I resolved it by setting the ValidateExternalMetadata property within the component to False.

write multiple lines in a file in python

another way which, at least to me, seems more intuitive:

target.write('''line 1
line 2
line 3''')

tqdm in Jupyter Notebook prints new progress bars repeatedly

For everyone who is on windows and couldn't solve the duplicating bars issue with any of the solutions mentioned here. I had to install the colorama package as stated in tqdm's known issues which fixed it.

pip install colorama

Try it with this example:

from tqdm import tqdm
from time import sleep

for _ in tqdm(range(5), "All", ncols = 80, position = 0):
    for _ in tqdm(range(100), "Sub", ncols = 80, position = 1, leave = False):
        sleep(0.01)

Which will produce something like:

All:  60%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                | 3/5 [00:03<00:02,  1.02s/it]
Sub:  50%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦                  | 50/100 [00:00<00:00, 97.88it/s]

Post-increment and Pre-increment concept?

It's pretty simple. Both will increment the value of a variable. The following two lines are equal:

x++;
++x;

The difference is if you are using the value of a variable being incremented:

x = y++;
x = ++y;

Here, both lines increment the value of y by one. However, the first one assigns the value of y before the increment to x, and the second one assigns the value of y after the increment to x.

So there's only a difference when the increment is also being used as an expression. The post-increment increments after returning the value. The pre-increment increments before.

Set div height to fit to the browser using CSS

Man, try the min-height.

.div1 {
    float: left;
    height: 100%;
    min-height: 100%;
    width: 25%;
}
.div2 {
    float: left;
    height: 100%;
    min-height: 100%;
    width: 75%;
}

jquery beforeunload when closing (not leaving) the page?

You can do this by using JQuery.

For example ,

<a href="your URL" id="navigate"> click here </a>

Your JQuery will be,

$(document).ready(function(){

    $('a').on('mousedown', stopNavigate);

    $('a').on('mouseleave', function () {
           $(window).on('beforeunload', function(){
                  return 'Are you sure you want to leave?';
           });
    });
});

function stopNavigate(){    
    $(window).off('beforeunload');
}

And to get the Leave message alert will be,

$(window).on('beforeunload', function(){
      return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){

         logout();

});

This solution works in all browsers and I have tested it.

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

Why do I need to do `--set-upstream` all the time?

git branch --set-upstream-to=origin/master<branch_name>

How to vertically align text inside a flexbox?

RESULT

enter image description here

HTML

<ul class="list">
  <li>This is the text</li>
  <li>This is another text</li>
  <li>This is another another text</li>
</ul>

Use align-items instead of align-self and I also added flex-direction to column.

CSS

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.list {
  display: flex;
  justify-content: center;
  flex-direction: column;  /* <--- I added this */
  align-items: center;   /* <--- Change here */
  height: 100px;
  width: 100%;
  background: silver;
}

.list li {  
  background: gold;
  height: 20%; 
}

How do I scroll to an element using JavaScript?

The best, shortest answer that what works even with animation effects:

var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});

If you have a fixed nav bar, just subtract its height from top value, so if your fixed bar height is 70px, line 2 will look like:

window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});

Explanation: Line 1 gets the element position Line 2 scroll to element position; behavior property adds a smooth animated effect

Shorthand for if-else statement

Try like

var hasName = 'N';
if (name == "true") {
    hasName = 'Y';
}

Or even try with ternary operator like

var hasName = (name == "true") ? "Y" : "N" ;

Even simply you can try like

var hasName = (name) ? "Y" : "N" ;

Since name has either Yes or No but iam not sure with it.

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

Why is JsonRequestBehavior needed?

By default Jsonresult "Deny get"

Suppose if we have method like below

  [HttpPost]
 public JsonResult amc(){}

By default it "Deny Get".

In the below method

public JsonResult amc(){}

When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.

public JsonResult amc()
{
 return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}

What is the advantage of using REST instead of non-REST HTTP?

Query-strings can be ignored by search engines.

Deploy a project using Git push

My take on Christians solution.

git archive --prefix=deploy/  master | tar -x -C $TMPDIR | rsync $TMPDIR/deploy/ --copy-links -av [email protected]:/home/user/my_app && rm -rf $TMPDIR/deploy
  • Archives the master branch into tar
  • Extracts tar archive into deploy dir in system temp folder.
  • rsync changes into server
  • delete deploy dir from temp folder.

Team Build Error: The Path ... is already mapped to workspace

I tried all the following solutions such as :

  1. Use sidekicks to delete WS.
  2. Use tf commands to delete remote server workspaces.
  3. Delete the TFS cache folder.

The following worked for me:

tf workspaces /remove:*

regular expression for Indian mobile numbers

^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$

Hi, This is regex for indian local mobile number validation and for Indian international .

starting with 9,8,7 you can add more as well.

you can test it using https://regex101.com/

Valid number are.

9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344

List of installed gems?

Gem::Specification.map {|a| a.name}

However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:

def all_installed_gems
   Gem::Specification.all = nil    
   all = Gem::Specification.map{|a| a.name}  
   Gem::Specification.reset
   all
end

What's the difference between unit, functional, acceptance, and integration tests?

Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.

Unit Tests

Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:

  • Call out into (non-trivial) collaborators
  • Access the network
  • Hit a database
  • Use the file system
  • Spin up a thread
  • etc.

Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do.

In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...

Integration Tests

Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly.

If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.

The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.

Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!

Functional Tests

Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4".

Acceptance Tests

Acceptance testing seems to be split into two types:

Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome.

The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky.

Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.

Conclusion

They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.

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

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

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

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

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

enter image description here

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

Download a specific tag with Git

git fetch <gitserver> <remotetag>:<localtag>

===================================

I just did this. First I made sure I knew the tag name spelling.

git ls-remote --tags gitserver; : or origin, whatever your remote is called

This gave me a list of tags on my git server to choose from. The original poster already knew his tag's name so this step is not necessary for everyone. The output looked like this, though the real list was longer.

8acb6864d10caa9baf25cc1e4857371efb01f7cd    refs/tags/v5.2.2.2
f4ba9d79e3d760f1990c2117187b5010e92e1ea2    refs/tags/v5.2.3.1
8dd05466201b51fcaf4ca85897347d82fcb29518    refs/tags/Fix_109
9b5087090d9077c10ba22d99d5ce90d8a45c50a3    refs/tags/Fix_110

I picked the tag I wanted and fetched that and nothing more as follows.

git fetch gitserver Fix_110

I then tagged this on my local machine, giving my tag the same name.

git tag Fix_110 FETCH_HEAD

I didn't want to clone the remote repository as other people have suggested doing, as the project I am working on is large and I want to develop in a nice clean environment. I feel this is closer to the original questions "I'm trying to figure out how do download A PARTICULAR TAG" than the solution which suggests cloning the whole repository. I don't see why anyone should have to have a copy of Windows NT and Windows 8.1 source code if they want to look at DOS 0.1 source code (for example).

I also didn't want to use CHECKOUT as others have suggested. I had a branch checked out and didn't want to affect that. My intention was to fetch the software I wanted so that I could cherry-pick something and add that to my development.

There is probably a way to fetch the tag itself rather than just a copy of the commit that was tagged. I had to tag the fetched commit myself. EDIT: Ah yes, I have found it now.

git fetch gitserver Fix_110:Fix_110

Where you see the colon, that is remote-name:local-name and here they are the tag names. This runs without upsetting the working tree etc. It just seems to copy stuff from the remote to the local machine so you have your own copy.

git fetch gitserver --dry-run Fix_110:Fix_110

with the --dry-run option added will let you have a look at what the command would do, if you want to verify its what you want. So I guess a simple

git fetch gitserver remotetag:localtag

is the real answer.

=

A separate note about tags ... When I start something new I usually tag the empty repository after git init, since

git rebase -i XXXXX 

requires a commit, and the question arises "how do you rebase changes that include your first software change?" So when I start working I do

git init
touch .gitignore
[then add it and commit it, and finally]
git tag EMPTY

i.e. create a commit before my first real change and then later use

git rebase -i EMPTY 

if I want to rebase all my work, including the first change.

Converting A String To Hexadecimal In Java

Use DatatypeConverter.printHexBinary():

public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
    byte[] myBytes = text.getBytes("UTF-8");

    return DatatypeConverter.printHexBinary(myBytes);
}

Example usage:

System.out.println(toHexadecimal("Hello StackOverflow"));

Prints:

48656C6C6F20537461636B4F766572666C6F77

Note: This causes a little extra trouble with Java 9 and newer since the API is not included by default. For reference e.g. see this GitHub issue.

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Listing a public key in .ssh/authorized_keys is necessary, but not sufficient for sshd (server) to accept it. If your private key is passphrase-protected, you'll need to give ssh (client) the passphrase every time. Or you can use ssh-agent, or a GNOME equivalent.

Your updated trace is consistent with a passphrase-protected private key. See ssh-agent, or use ssh-keygen -p.

subtract two times in python

The python timedelta library should do what you need. A timedelta is returned when you subtract two datetime instances.

import datetime
dt_started = datetime.datetime.utcnow()

# do some stuff

dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())

encapsulation vs abstraction real world example

Abstraction

We use many abstractions in our day-to-day lives.Consider a car.Most of us have an abstract view of how a car works.We know how to interact with it to get it to do what we want it to do: we put in gas, turn a key, press some pedals, and so on. But we don't necessarily understand what is going on inside the car to make it move and we don't need to. Millions of us use cars everyday without understanding the details of how they work.Abstraction helps us get to school or work!

A program can be designed as a set of interacting abstractions. In Java, these abstractions are captured in classes. The creator of a class obviusly has to know its interface, just as the driver of a car can use the vehicle without knowing how the engine works.

Encapsulation

Consider a Banking system.Banking system have properties like account no,account type,balance ..etc. If someone is trying to change the balance of the account,attempt can be successful if there is no encapsulation. Therefore encapsulation allows class to have complete control over their properties.

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)