Programs & Examples On #Google local search

anaconda update all possible packages?

TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another

You are right:

conda update --all

is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).

Dependency conflicts

But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.

e.g. X requires Y <5.0, so Y will never be >= 5.0

That's why you 'cannot' upgrade them all.

Resolving

To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.

A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.

Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:

X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0

So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.

(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)

So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!


1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv and then conda activate myenv). Executing conda update --all inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I my case the problem was a residual dump file in the database directory. That file was probably generated during a backup script test I had been working on. Once I manually deleted the file I could then drop the database.

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

JVM property -Dfile.encoding=UTF8 or UTF-8?

If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8), if you don't set it on the command-line with -Dfile.encoding, the JDK will default file.encoding and the default Charset like this:

System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

... yields:

file.encoding: UTF-8
defaultCharset: UTF-8

... suggesting the default is UTF-8 on such a platform.

Additionally, if java.nio.charset.Charset.defaultCharset() finds file.encoding not-set, it looks for java.nio.charset.Charset.forName("UTF-8"), suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.

If you run the same program on the same platform with java -Dfile.encoding=UTF8, without the hypen, it yields:

file.encoding: UTF8
defaultCharset: UTF-8

... noting that the default charset has been canonicalized from UTF8 to UTF-8.

How to tell when UITableView has completed ReloadData?

The reload happens during the next layout pass, which normally happens when you return control to the run loop (after, say, your button action or whatever returns).

So one way to run something after the table view reloads is simply to force the table view to perform layout immediately:

[self.tableView reloadData];
[self.tableView layoutIfNeeded];
 NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

Another way is to schedule your after-layout code to run later using dispatch_async:

[self.tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
     NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection:([self.tableView numberOfSections]-1)];

    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
});

UPDATE

Upon further investigation, I find that the table view sends tableView:numberOfSections: and tableView:numberOfRowsInSection: to its data source before returning from reloadData. If the delegate implements tableView:heightForRowAtIndexPath:, the table view also sends that (for each row) before returning from reloadData.

However, the table view does not send tableView:cellForRowAtIndexPath: or tableView:headerViewForSection until the layout phase, which happens by default when you return control to the run loop.

I also find that in a tiny test program, the code in your question properly scrolls to the bottom of the table view, without me doing anything special (like sending layoutIfNeeded or using dispatch_async).

How to make UIButton's text alignment center? Using IB

For those of you who are now using iOS 6 or higher, UITextAlignmentCenter has been deprecated. It is now NSTextAlignmentCenter

EXAMPLE: mylabel.textAlignment = NSTextAlignmentCenter; Works perfectly.

Java: splitting a comma-separated string but ignoring commas in quotes

Try:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
        String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

Output:

> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"

In other words: split on the comma only if that comma has zero, or an even number of quotes ahead of it.

Or, a bit friendlier for the eyes:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";

        String otherThanQuote = " [^\"] ";
        String quotedString = String.format(" \" %s* \" ", otherThanQuote);
        String regex = String.format("(?x) "+ // enable comments, ignore white spaces
                ",                         "+ // match a comma
                "(?=                       "+ // start positive look ahead
                "  (?:                     "+ //   start non-capturing group 1
                "    %s*                   "+ //     match 'otherThanQuote' zero or more times
                "    %s                    "+ //     match 'quotedString'
                "  )*                      "+ //   end group 1 and repeat it zero or more times
                "  %s*                     "+ //   match 'otherThanQuote'
                "  $                       "+ // match the end of the string
                ")                         ", // stop positive look ahead
                otherThanQuote, quotedString, otherThanQuote);

        String[] tokens = line.split(regex, -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

which produces the same as the first example.

EDIT

As mentioned by @MikeFHay in the comments:

I prefer using Guava's Splitter, as it has saner defaults (see discussion above about empty matches being trimmed by String#split(), so I did:

Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))

How to change the Title of the window in Qt?

I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show(); is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.

int main(int argc, char *argv[]) 
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();

return a.exec();
}

Can I run a 64-bit VMware image on a 32-bit machine?

Yes, running a 64-bit OS in VMWare is possible from a 32-bit OS if you have a 64 bit processor.

I have an old Intel Core 2 Duo with Windows XP Professional 2002 running on it, and I got it to work.

First of all, see if your CPU is capable of running a 64-bit OS. Search for 'Processor check for 64-bit compatibility' on the VMware site. Run the program.

If it says your processor is capable, restart your computer and go into the BIOS and see if you have 'Virtualization' and are able to enable it. I was able to and got Windows Server 2008 R2 running under VMware on this old laptop.

I hope it works for you!

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

Countercheck if boostrap/cache/config.php database details are correct. That should give you an hint if they are.

If they are not, then you need to clear the cache using the following steps :

  1. rm -fr bootstrap/cache/*
  2. php artisan optimize

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

How to increase font size in NeatBeans IDE?

You can create your own shortcut for increase/Decrease Netbeans Fonts size

just goto Tools > Options > Keymaps than search zoom

click on three (...) dot and click Edit

press your_shortcut_keys ( what ever shortcut you want to set)

How to query MongoDB with "like"?

In Go and the mgo driver:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

where result is the struct instance of the sought after type

Selenium using Python - Geckodriver executable needs to be in PATH

I've actually discovered you can use the latest geckodriver without putting it in the system path. Currently I'm using

https://github.com/mozilla/geckodriver/releases/download/v0.12.0/geckodriver-v0.12.0-win64.zip

Firefox 50.1.0

Python 3.5.2

Selenium 3.0.2

Windows 10

I'm running a VirtualEnv (which I manage using PyCharm, and I assume it uses Pip to install everything).

In the following code I can use a specific path for the geckodriver using the executable_path parameter (I discovered this by having a look in Lib\site-packages\selenium\webdriver\firefox\webdriver.py ). Note I have a suspicion that the order of parameter arguments when calling the webdriver is important, which is why the executable_path is last in my code (the second to last line off to the far right).

You may also notice I use a custom Firefox profile to get around the sec_error_unknown_issuer problem that you will run into if the site you're testing has an untrusted certificate. See How to disable Firefox's untrusted connection warning using Selenium?

After investigation it was found that the Marionette driver is incomplete and still in progress, and no amount of setting various capabilities or profile options for dismissing or setting certificates was going to work. So it was just easier to use a custom profile.

Anyway, here's the code on how I got the geckodriver to work without being in the path:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

#you probably don't need the next 3 lines they don't seem to work anyway
firefox_capabilities['handleAlerts'] = True
firefox_capabilities['acceptSslCerts'] = True
firefox_capabilities['acceptInsecureCerts'] = True

# In the next line I'm using a specific Firefox profile because
# I wanted to get around the sec_error_unknown_issuer problems with the new Firefox and Marionette driver
# I create a Firefox profile where I had already made an exception for the site I'm testing
# see https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles#w_starting-the-profile-manager

ffProfilePath = 'D:\Work\PyTestFramework\FirefoxSeleniumProfile'
profile = webdriver.FirefoxProfile(profile_directory=ffProfilePath)
geckoPath = 'D:\Work\PyTestFramework\geckodriver.exe'
browser = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities, executable_path=geckoPath)
browser.get('http://stackoverflow.com')

How do I POST urlencoded form data with $http without jQuery?

I think you need to do is to transform your data from object not to JSON string, but to url params.

From Ben Nadel's blog.

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Example from here.

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).then(function () {});

UPDATE

To use new services added with AngularJS V1.4, see

How to send an email with Gmail as provider using Python?

There is a gmail API now, which lets you send email, read email and create drafts via REST. Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.

  • Of course, email should be handed off to a non-webserver queue, but it's nice to have options.

It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.

Here is a gist demonstrating it:

https://gist.github.com/timrichardson/1154e29174926e462b7a

How do I remove a MySQL database?

I needed to correct the privileges.REVOKE ALL PRIVILEGES ONlogs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ONlogs.* TO 'root'@'root'WITH GRANT OPTION;

"git pull" or "git merge" between master and development branches

The best approach for this sort of thing is probably git rebase. It allows you to pull changes from master into your development branch, but leave all of your development work "on top of" (later in the commit log) the stuff from master. When your new work is complete, the merge back to master is then very straightforward.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How do I exit from the text window in Git?

First type

 i

to enter the commit message then press ESC then type

 :wq

to save the commit message and to quit. Or type

 :q!

to quit without saving the message.

How to export all data from table to an insertable sql format?

Another way to dump data as file from table by DumpDataFromTable sproc

EXEC dbo.DumpDataFromTable
     @SchemaName = 'dbo'
    ,@TableName = 'YourTableName'
    ,@PathOut = N'c:\tmp\scripts\' -- folder must exist !!!'

Note: SQL must have permission to create files, if is not set-up then exec follow line once

EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

By this script you can call the sproc: DumpDataFromTable.sql and dump more tables in one go, instead of doing manually one by one from Management Studio

By default the format of generated scrip will be like

INSERT INTO <TableName> SELECT <Values>

Or you can change the generated format into

SELECT ... FROM

by setting variable @BuildMethod = 2

full sproc code:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DumpDataFromTable]') AND type in (N'P', N'PC'))
    DROP PROCEDURE dbo.[DumpDataFromTable]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:    Oleg Ciobanu
-- Create date: 20171214
-- Version 1.02
-- Description:
-- dump data in 2 formats
-- @BuildMethod = 1 INSERT INTO format
-- @BuildMethod = 2 SELECT * FROM format
--
-- SQL must have permission to create files, if is not set-up then exec follow line once
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
--
-- =============================================
CREATE PROCEDURE [dbo].[DumpDataFromTable]
(
     @SchemaName nvarchar(128) --= 'dbo'
    ,@TableName nvarchar(128) --= 'testTable'
    ,@WhereClause nvarchar (1000) = '' -- must start with AND
    ,@BuildMethod int = 1 -- taking values 1 for INSERT INTO forrmat or 2 for SELECT from value Table
    ,@PathOut nvarchar(250) = N'c:\tmp\scripts\' -- folder must exist !!!'
    ,@AsFileNAme nvarchar(250) = NULL -- if is passed then will use this value as FileName
    ,@DebugMode int = 0
)
AS
BEGIN  
    SET NOCOUNT ON;

        -- run follow next line if you get permission deny  for sp_OACreate,sp_OAMethod
        -- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

    DECLARE @Sql nvarchar (max)
    DECLARE @SqlInsert nvarchar (max) = ''
    DECLARE @Columns nvarchar(max)
    DECLARE @ColumnsCast nvarchar(max)

    -- cleanUp/prepraring data
    SET @SchemaName = REPLACE(REPLACE(@SchemaName,'[',''),']','')
    SET @TableName = REPLACE(REPLACE(@TableName,'[',''),']','')
    SET @AsFileNAme = NULLIF(@AsFileNAme,'')
    SET @AsFileNAme = REPLACE(@AsFileNAme,'.','_')
    SET @AsFileNAme = COALESCE(@PathOut + @AsFileNAme + '.sql', @PathOut + @SchemaName + ISNULL('_' + @TableName,N'') + '.sql')


    --debug
    IF @DebugMode = 1
        PRINT @AsFileNAme

        -- Create temp SP what will be responsable for generating script files
    DECLARE @PRC_WritereadFile VARCHAR(max) =
        'IF EXISTS (SELECT * FROM sys.objects WHERE type = ''P'' AND name = ''PRC_WritereadFile'')
       BEGIN
          DROP  Procedure  PRC_WritereadFile
       END;'
    EXEC  (@PRC_WritereadFile)
       -- '  
    SET @PRC_WritereadFile =
    'CREATE Procedure PRC_WritereadFile (
        @FileMode INT -- Recreate = 0 or Append Mode 1
       ,@Path NVARCHAR(1000)
       ,@AsFileNAme NVARCHAR(500)
       ,@FileBody NVARCHAR(MAX)   
       )
    AS
        DECLARE @OLEResult INT
        DECLARE @FS INT
        DECLARE @FileID INT
        DECLARE @hr INT
        DECLARE @FullFileName NVARCHAR(1500) = @Path + @AsFileNAme

        -- Create Object
        EXECUTE @OLEResult = sp_OACreate ''Scripting.FileSystemObject'', @FS OUTPUT
        IF @OLEResult <> 0 BEGIN
            PRINT ''Scripting.FileSystemObject''
            GOTO Error_Handler
        END    

        IF @FileMode = 0 BEGIN  -- Create
            EXECUTE @OLEResult = sp_OAMethod @FS,''CreateTextFile'',@FileID OUTPUT, @FullFileName
            IF @OLEResult <> 0 BEGIN
                PRINT ''CreateTextFile''
                GOTO Error_Handler
            END
        END ELSE BEGIN          -- Append
            EXECUTE @OLEResult = sp_OAMethod @FS,''OpenTextFile'',@FileID OUTPUT, @FullFileName, 8, 0 -- 8- forappending
            IF @OLEResult <> 0 BEGIN
                PRINT ''OpenTextFile''
                GOTO Error_Handler
            END            
        END

        EXECUTE @OLEResult = sp_OAMethod @FileID, ''WriteLine'', NULL, @FileBody
        IF @OLEResult <> 0 BEGIN
            PRINT ''WriteLine''
            GOTO Error_Handler
        END     

        EXECUTE @OLEResult = sp_OAMethod @FileID,''Close''
        IF @OLEResult <> 0 BEGIN
            PRINT ''Close''
            GOTO Error_Handler
        END

        EXECUTE sp_OADestroy @FS
        EXECUTE sp_OADestroy @FileID

        GOTO Done

        Error_Handler:
            DECLARE @source varchar(30), @desc varchar (200)       
            EXEC @hr = sp_OAGetErrorInfo null, @source OUT, @desc OUT
            PRINT ''*** ERROR ***''
            SELECT OLEResult = @OLEResult, hr = CONVERT (binary(4), @hr), source = @source, description = @desc

       Done:
    ';
        -- '
    EXEC  (@PRC_WritereadFile) 
    EXEC PRC_WritereadFile 0 /*Create*/, '', @AsFileNAme, ''


    ;WITH steColumns AS (
        SELECT
            1 as rn,
            c.ORDINAL_POSITION
            ,c.COLUMN_NAME as ColumnName
            ,c.DATA_TYPE as ColumnType
        FROM INFORMATION_SCHEMA.COLUMNS c
        WHERE 1 = 1
        AND c.TABLE_SCHEMA = @SchemaName
        AND c.TABLE_NAME = @TableName
    )

    --SELECT *

       SELECT
            @ColumnsCast = ( SELECT
                                    CASE WHEN ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                        THEN
                                            'convert(nvarchar(1001), s.[' + ColumnName + ']' + ' , 121) AS [' + ColumnName + '],'
                                            --,convert(nvarchar, [DateTimeScriptApplied], 121) as [DateTimeScriptApplied]
                                        ELSE
                                            'CAST(s.[' + ColumnName + ']' + ' AS NVARCHAR(1001)) AS [' + ColumnName + '],'
                                    END
                                     as 'data()'                                  
                                    FROM
                                      steColumns t2
                                    WHERE 1 =1
                                      AND t1.rn = t2.rn
                                    FOR xml PATH('')
                                   )
            ,@Columns = ( SELECT
                                    '[' + ColumnName + '],' as 'data()'                                  
                                    FROM
                                      steColumns t2
                                    WHERE 1 =1
                                      AND t1.rn = t2.rn
                                    FOR xml PATH('')
                                   )

    FROM steColumns t1

    -- remove last char
    IF lEN(@Columns) > 0 BEGIN
        SET @Columns = SUBSTRING(@Columns, 1, LEN(@Columns)-1);
        SET @ColumnsCast = SUBSTRING(@ColumnsCast, 1, LEN(@ColumnsCast)-1);
    END

    -- debug
    IF @DebugMode = 1 BEGIN
        print @ColumnsCast
        print @Columns
        select @ColumnsCast ,  @Columns
    END

    -- build unpivoted Data
    SET @SQL = '
    SELECT
        u.rn
        , c.ORDINAL_POSITION as ColumnPosition
        , c.DATA_TYPE as ColumnType
        , u.ColumnName
        , u.ColumnValue
    FROM
    (SELECT
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
    '
    + CHAR(13) + @ColumnsCast
    + CHAR(13) + 'FROM [' + @SchemaName + '].[' + @TableName + '] s'
    + CHAR(13) + 'WHERE 1 = 1'
    + CHAR(13) + COALESCE(@WhereClause,'')
    + CHAR(13) + ') tt
    UNPIVOT
    (
      ColumnValue
      FOR ColumnName in (
    ' + CHAR(13) + @Columns
    + CHAR(13)
    + '
     )
    ) u

    LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.COLUMN_NAME = u.ColumnName
        AND c.TABLE_SCHEMA = '''+ @SchemaName + '''
        AND c.TABLE_NAME = ''' + @TableName +'''
    ORDER BY u.rn
            , c.ORDINAL_POSITION
    '

    -- debug
    IF @DebugMode = 1 BEGIN
        print @Sql     
        exec (@Sql)
    END

    -- prepare data for cursor

    IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
        DROP TABLE #tmp
    CREATE TABLE #tmp
    (
        rn bigint
        ,ColumnPosition int
        ,ColumnType varchar (128)
        ,ColumnName varchar (128)
        ,ColumnValue nvarchar (2000) -- I hope this size will be enough for storring values
    )
    SET @Sql = 'INSERT INTO  #tmp ' + CHAR(13)  + @Sql

    -- debug
    IF @DebugMode = 1 BEGIN
        print @Sql
    END

    EXEC (@Sql)

 -- Insert dummy rec, otherwise will not proceed the last rec :)
INSERT INTO #tmp (rn)
SELECT MAX(rn) +  1 
FROM #tmp   

    IF @DebugMode = 1 BEGIN
        SELECT * FROM #tmp
    END

    DECLARE @rn bigint
        ,@ColumnPosition int
        ,@ColumnType varchar (128)
        ,@ColumnName varchar (128)
        ,@ColumnValue nvarchar (2000)
        ,@i int = -1 -- counter/flag
        ,@ColumnsInsert varchar(max) = NULL
        ,@ValuesInsert nvarchar(max) = NULL

    DECLARE cur CURSOR FOR
    SELECT rn, ColumnPosition, ColumnType, ColumnName, ColumnValue
    FROM #tmp
    ORDER BY rn, ColumnPosition -- note order is really important !!!
    OPEN cur

    FETCH NEXT FROM cur
    INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

    IF @BuildMethod = 1
    BEGIN
        SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
        SET @SqlInsert = ''
    END
    ELSE BEGIN
        SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
        SET @SqlInsert = @SqlInsert
                        + 'SELECT *'
                        + CHAR(13) + 'FROM ('
                        + CHAR(13) + 'VALUES'
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
        SET @SqlInsert = NULL
    END

    SET @i = @rn

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@i <> @rn) -- is a new row
        BEGIN
            IF @BuildMethod = 1
            -- build as INSERT INTO -- as Default
            BEGIN
                SET @SqlInsert = 'INSERT INTO [' + @SchemaName + '].[' + @TableName + '] ('
                                + CHAR(13) + @ColumnsInsert + ')'
                                + CHAR(13) + 'VALUES ('
                                + @ValuesInsert
                                + CHAR(13) + ');'
            END
            ELSE
            BEGIN
                -- build as Table select
                IF (@i <> @rn) -- is a new row
                BEGIN
                    SET @SqlInsert = COALESCE(@SqlInsert + ',','') +  '(' + @ValuesInsert+ ')'
                    EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
                    SET @SqlInsert = '' -- in method 2 we should clear script
                END            
            END
            -- debug
            IF @DebugMode = 1
                print @SqlInsert
            EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert

            -- we have new row
            -- initialise variables
            SET @i = @rn
            SET @ColumnsInsert = NULL
            SET @ValuesInsert = NULL
        END

        -- build insert values
        IF (@i = @rn) -- is same row
        BEGIN
            SET @ColumnsInsert = COALESCE(@ColumnsInsert + ',','') + '[' + @ColumnName + ']'
            SET @ValuesInsert =  CASE                              
                                    -- date
                                    --WHEN
                                    --  @ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                    --THEN
                                    --  COALESCE(@ValuesInsert + ',','') + '''''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''''
                                    -- numeric
                                    WHEN
                                        @ColumnType IN ('bit','tinyint','smallint','int','bigint'
                                                        ,'money','real','','float','decimal','numeric','smallmoney')
                                    THEN
                                        COALESCE(@ValuesInsert + ',','') + '' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''
                                    -- other types treat as string
                                    ELSE
                                        COALESCE(@ValuesInsert + ',','') + '''' + ISNULL(RTRIM( 
                                                                                            -- escape single quote
                                                                                            REPLACE(@ColumnValue, '''', '''''') 
                                                                                              ),'NULL') + ''''         
                                END
        END


        FETCH NEXT FROM cur
        INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

        -- debug
        IF @DebugMode = 1
        BEGIN
            print CAST(@rn AS VARCHAR) + '-' + CAST(@ColumnPosition AS VARCHAR)
        END
    END
    CLOSE cur
    DEALLOCATE cur

    IF @BuildMethod = 1
    BEGIN
        PRINT 'ignore'
    END
    ELSE BEGIN
        SET @SqlInsert = CHAR(13) + ') AS vtable '
                        + CHAR(13) + ' (' + @Columns
                        + CHAR(13) + ')'
        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
        SET @SqlInsert = NULL
    END
    PRINT 'Done: ' + @AsFileNAme
END

Or can be downloaded latest version from https://github.com/Zindur/MSSQL-DumpTable/tree/master/Scripts

Twitter Bootstrap - full width navbar

Put your <nav>element out from the <div class='container-fluid'>. Ex :-

_x000D_
_x000D_
<nav>_x000D_
 ......nav content goes here_x000D_
<nav>_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <div>_x000D_
   ........ other content goes here_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using custom std::set comparator

1. Modern C++20 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;

We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Online demo

2. Modern C++11 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);

Before C++20 we need to pass lambda as argument to set constructor

Online demo

3. Similar to first solution, but with function instead of lambda

Make comparator as usual boolean function

bool cmp(int a, int b) {
    return ...;
}

Then use it, either this way:

std::set<int, decltype(cmp)*> s(cmp);

Online demo

or this way:

std::set<int, decltype(&cmp)> s(&cmp);

Online demo

4. Old solution using struct with () operator

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }
};

// ...
// later
std::set<int, cmp> s;

Online demo

5. Alternative solution: create struct from boolean function

Take boolean function

bool cmp(int a, int b) {
    return ...;
}

And make struct from it using std::integral_constant

#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

Finally, use the struct as comparator

std::set<X, Cmp> set;

Online demo

Convert List<String> to List<Integer> directly

Using Java8:

stringList.stream().map(Integer::parseInt).collect(Collectors.toList());

How to convert integer into date object python?

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

Call Javascript onchange event by programmatically changing textbox value

This is an old question, and I'm not sure if it will help, but I've been able to programatically fire an event using:

if (document.createEvent && ctrl.dispatchEvent) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", true, true);
    ctrl.dispatchEvent(evt); // for DOM-compliant browsers
} else if (ctrl.fireEvent) {
    ctrl.fireEvent("onchange"); // for IE
}

How to secure database passwords in PHP?

If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.

You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.

Java Replacing multiple different substring in a string at once (or in the most efficient way)

If the string you are operating on is very long, or you are operating on many strings, then it could be worthwhile using a java.util.regex.Matcher (this requires time up-front to compile, so it won't be efficient if your input is very small or your search pattern changes frequently).

Below is a full example, based on a list of tokens taken from a map. (Uses StringUtils from Apache Commons Lang).

Map<String,String> tokens = new HashMap<String,String>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");

String template = "%cat% really needs some %beverage%.";

// Create pattern of the format "%(cat|beverage)%"
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);

StringBuffer sb = new StringBuffer();
while(matcher.find()) {
    matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);

System.out.println(sb.toString());

Once the regular expression is compiled, scanning the input string is generally very quick (although if your regular expression is complex or involves backtracking then you would still need to benchmark in order to confirm this!)

How to update Android Studio automatically?

If you go to help>>check for updates it will tell you if there's an update.

You don't have to change from the stable channel. If you aren't offered an update and restart button, kindly close the window and try again. After about 4 or 5 checks like this, it will eventually show you update and restart button.

Why? because google.

What is the right way to check for a null string in Objective-C?

If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:

static inline BOOL IsEmpty(id object) {
    return object == nil
        || ([object respondsToSelector:@selector(length)]
        && [(NSData *) object length] == 0)
        || ([object respondsToSelector:@selector(count)]
        && [(NSArray *) object count] == 0);
}

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

delete a column with awk or sed

GNU awk 4.1

awk -i inplace NF--

This will remove the last field of each line.

How to construct a WebSocket URI relative to the page URI?

Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL

Works with http(s), ports etc.

var url = new URL('/path/to/websocket', window.location.href);

url.protocol = url.protocol.replace('http', 'ws');

url.href // => ws://www.example.com:9999/path/to/websocket

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

SimpleDateFormat("MM-dd-yyyy");

instead of

SimpleDateFormat("mm-dd-yyyy");

because MM points Month, mm points minutes

SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);

Can I use VARCHAR as the PRIMARY KEY?

It depends on the specific use case.

If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:

CREATE TABLE Foo 
(
    FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
    Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
    LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table...&nbsp;
)

Of course, when your table is not static at all, using INT as primary key is the best solution.

Connect to SQL Server through PDO using SQL Server Driver

Figured this out. Pretty simple:

 new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]",  "[username]", "[password]");

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

I ended up using a normal hyperlink along with Url.Action, as in:

<a href='<%= Url.Action("Show", new { controller = "Browse", id = node.Id }) %>'
  data-nodeId='<%= node.Id %>'>
  <%: node.Name %>
</a>

It's uglier, but you've got a little more control over the a tag, which is sometimes useful in heavily AJAXified sites.

HTH

How to call webmethod in Asp.net C#

The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..

Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

Keyboard shortcut to clear cell output in Jupyter notebook

Add following at start of cell and run it:

from IPython.display import clear_output
clear_output(wait=True)

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Wait some seconds without blocking UI execution

Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

Thread.Sleep(1);

before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

private void WaitNSeconds(int seconds)
{
    if (seconds < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(seconds);
    while (DateTime.Now < _desired) {
         Thread.Sleep(1);
         System.Windows.Forms.Application.DoEvents();
    }
}

*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

Emulator error: This AVD's configuration is missing a kernel file

I had the same problem. In my case it turned out I had installed another version of the sdk alongside the version provided by Android Studio. Changing my ANDROID_SDK_ROOT environment variable to the original value fixed it for me.

Add st, nd, rd and th (ordinal) suffix to a number

This is for one liners and lovers of es6

let i= new Date().getDate 

// I can be any number, for future sake we'll use 9

const j = I % 10;
const k = I % 100;

i = `${i}${j === 1 &&  k !== 11 ? 'st' : j === 2 && k !== 12 ? 'nd' : j === 3 && k !== 13 ? 'rd' : 'th'}`}

console.log(i) //9th

Another option for +be number would be:

console.log(["st","nd","rd"][((i+90)%100-10)%10-1]||"th"]

Also to get rid of the ordinal prefix just use these:

console.log(i.parseInt("8th"))

console.log(i.parseFloat("8th"))

feel free to modify to suit you need

How to convert XML to JSON in Python?

xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.

Once you have that data structure, you can serialize it to JSON:

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

How to access route, post, get etc. parameters in Zend Framework 2

The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',
                ),
            ),
        ),

and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend

$this->params()->fromPost('paramname'); 

didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');
print_r(json_decode($content));

I got my json array in the end. Hope this helps.

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

You can convert it with JS:

$('.image-class').each(function(){
    var processing = $(this).attr('src');
    $(this).parent().css({'background-image':'url('+processing+')'});
    $(this).hide();
});

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

What does the "assert" keyword do?

Although I have read a lot documentation about this one, I'm still confusing on how, when, and where to use it.

Make it very simple to understand:

When you have a similar situation like this:

    String strA = null;
    String strB = null;
    if (2 > 1){
        strA = "Hello World";
    }

    strB = strA.toLowerCase(); 

You might receive warning (displaying yellow line on strB = strA.toLowerCase(); ) that strA might produce a NULL value to strB. Although you know that strB is absolutely won't be null in the end, just in case, you use assert to

1. Disable the warning.

2. Throw Exception error IF worst thing happens (when you run your application).

Sometime, when you compile your code, you don't get your result and it's a bug. But the application won't crash, and you spend a very hard time to find where is causing this bug.

So, if you put assert, like this:

    assert strA != null; //Adding here
    strB = strA .toLowerCase();

you tell the compiler that strA is absolutely not a null value, it can 'peacefully' turn off the warning. IF it is NULL (worst case happens), it will stop the application and throw a bug to you to locate it.

Limiting the number of characters in a JTextField

_x000D_
_x000D_
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                   _x000D_
if (jTextField1.getText().length()>=3) {_x000D_
            getToolkit().beep();_x000D_
            evt.consume();_x000D_
        }_x000D_
    }
_x000D_
_x000D_
_x000D_

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

ImportError: numpy.core.multiarray failed to import

Just fixed this issue. import c2 or import numpy was not working. Uninstalled the most current version of numpy. Tried to install numpy==1.15.2 just like specified above, did not work. Tried numpy==1.19.3 IT worked. I guess not all versions work perfectly with all versions of python and dependencies. So keep uninstalling and install one that works.

Subdomain on different host

sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g

mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain

anothersite.mydomain.com

of which the site is actually on another server then

login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11

And that's it.

How to write a PHP ternary operator

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

StringIO in Python3

when i write import StringIO it says there is no such module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

iptables LOG and DROP in one rule

for china GFW:

sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

How do you convert Html to plain text?

Depends on what you mean by "html." The most complex case would be complete web pages. That's also the easiest to handle, since you can use a text-mode web browser. See the Wikipedia article listing web browsers, including text mode browsers. Lynx is probably the best known, but one of the others may be better for your needs.

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

Working copy XXX locked and cleanup failed in SVN

Do not delete your solution!

in the .svn folder you have a file called lock it is 0 bytes long

You can delete all these files from all the .svn folders in your solution and it will work

It worked in my case

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

C++ convert hex string to signed integer

Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.

char hextob(char ch)
{
    if (ch >= '0' && ch <= '9') return ch - '0';
    if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
    return 0;
}
template<typename T>
T hextot(char* hex)
{
    T value = 0;
    for (size_t i = 0; i < sizeof(T)*2; ++i)
        value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
    return value;
};

Usage:

int main()
{
    char str[4] = {'f','f','f','f'};
    std::cout << hextot<int16_t>(str)  << "\n";
}

Note: the length of the string must be divisible by 2

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

I prefer to use ToString() and IFormatProvider.

double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));

Output: 10,000.30

hasNext in Python iterators?

If you really need a has-next functionality (because you're just faithfully transcribing an algorithm from a reference implementation in Java, say, or because you're writing a prototype that will need to be easily transcribed to Java when it's finished), it's easy to obtain it with a little wrapper class. For example:

class hn_wrapper(object):
  def __init__(self, it):
    self.it = iter(it)
    self._hasnext = None
  def __iter__(self): return self
  def next(self):
    if self._hasnext:
      result = self._thenext
    else:
      result = next(self.it)
    self._hasnext = None
    return result
  def hasnext(self):
    if self._hasnext is None:
      try: self._thenext = next(self.it)
      except StopIteration: self._hasnext = False
      else: self._hasnext = True
    return self._hasnext

now something like

x = hn_wrapper('ciao')
while x.hasnext(): print next(x)

emits

c
i
a
o

as required.

Note that the use of next(sel.it) as a built-in requires Python 2.6 or better; if you're using an older version of Python, use self.it.next() instead (and similarly for next(x) in the example usage). [[You might reasonably think this note is redundant, since Python 2.6 has been around for over a year now -- but more often than not when I use Python 2.6 features in a response, some commenter or other feels duty-bound to point out that they are 2.6 features, thus I'm trying to forestall such comments for once;-)]]

Tkinter module not found on Ubuntu

What worked for me in Ubuntu was actually just:

sudo apt-get install python3-tk

For python 3.6:

sudo apt-get install python3.6-tk

I didn't read anywhere, I simply tried it, as onteria_'s method didn't seem to work for me.

How to compress image size?

You can create bitmap with captured image as below:

Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);

Here you can specify width and height of the bitmap that you want to set to your ImageView. The height and width you can set according to the screen dpi of the device also, by reading the screen dpi of different devices programmatically.

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

How to create an Observable from static data similar to http one in Angular?

Perhaps you could try to use the of method of the Observable class:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

Inheritance and Overriding __init__ in python

In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...

class Female_Grandparent:
    def __init__(self):
        self.grandma_name = 'Grandma'

class Male_Grandparent:
    def __init__(self):
        self.grandpa_name = 'Grandpa'

class Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):
        Female_Grandparent.__init__(self)
        Male_Grandparent.__init__(self)

        self.parent_name = 'Parent Class'

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
#---------------------------------------------------------------------------------------#
        for cls in Parent.__bases__: # This block grabs the classes of the child
             cls.__init__(self)      # class (which is named 'Parent' in this case), 
                                     # and iterates through them, initiating each one.
                                     # The result is that each parent, of each child,
                                     # is automatically handled upon initiation of the 
                                     # dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#



g = Female_Grandparent()
print g.grandma_name

p = Parent()
print p.grandma_name

child = Child()

print child.grandma_name

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

How to pass arguments and redirect stdin from a file to program run in gdb?

Wouldn't it be nice to just type debug in front of any command to be able to debug it with gdb on shell level?

Below it this function. It even works with following:

"$program" "$@" < <(in) 1> >(out) 2> >(two) 3> >(three)

This is a call where you cannot control anything, everything is variable, can contain spaces, linefeeds and shell metacharacters. In this example, in, out, two, and three are arbitrary other commands which consume or produce data which must not be harmed.

Following bash function invokes gdb nearly cleanly in such an environment [Gist]:

debug()
{
  1000<&0 1001>&1 1002>&2 \
  0</dev/tty 1>/dev/tty 2>&0 \
  /usr/bin/gdb -q -nx -nw \
  -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" exec' \
  -ex r \
  --args "$@";
}

Example on how to apply this: Just type debug in front:

Before:

p=($'\n' $'I\'am\'evil' "  yay  ")
"b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

After:

p=($'\n' $'I\'am\'evil' "  yay  ")
debug "b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

That's it. Now it's an absolute no-brainer to debug with gdb. Except for a few details or more:

  • gdb does not quit automatically and hence keeps the IO redirection open until you exit gdb. But I call this a feature.

  • You cannot easily pass argv0 to the program like with exec -a arg0 command args. Following should do this trick: After exec-wrapper change "exec to "exec -a \"\${DEBUG_ARG0:-\$1}\".

  • There are FDs above 1000 open, which are normally closed. If this is a problem, change 0<&1000 1>&1001 2>&1002 to read 0<&1000 1>&1001 2>&1002 1000<&- 1001>&- 1002>&-

  • You cannot run two debuggers in parallel. There also might be issues, if some other command consumes /dev/tty (or STDIN). To fix that, replace /dev/tty with "${DEBUGTTY:-/dev/tty}". In some other TTY type tty; sleep inf and then use the printed TTY (i. E. /dev/pts/60) for debugging, as in DEBUGTTY=/dev/pts/60 debug command arg... That's the Power of Shell, get used to it!

Function explained:

  • 1000<&0 1001>&1 1002>&2 moves away the first 3 FDs
    • This assumes, that FDs 1000, 1001 and 1002 are free
  • 0</dev/tty 1>/dev/tty 2>&0 restores the first 3 FDs to point to your current TTY. So you can control gdb.
  • /usr/bin/gdb -q -nx -nw runs gdb invokes gdb on shell
  • -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" creates a startup wrapper, which restores the first 3 FDs which were saved to 1000 and above
  • -ex r starts the program using the exec-wrapper
  • --args "$@" passes the arguments as given

Wasn't that easy?

Cannot open include file with Visual Studio

For me, it helped to link the projects current directory as such:

In the properties -> C++ -> General window, instead of linking the path to the file in "additional include directories". Put "." and uncheck "inheret from parent or project defaults".

Hope this helps.

How can I align text directly beneath an image?

You can use HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

Resizing image in Java

            int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Start with the triangle...

    *
   **
  ***
 ****

representing 1+2+3+4 so far. Cut the triangle in half along one dimension...

     *
    **
  * **
 ** **

Rotate the smaller part 180 degrees, and stick it on top of the bigger part...

    **
    * 

     *
    **
    **
    **

Close the gap to get a rectangle.

At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.

Whatever the base of the triangle, the width of your rectangle is (base / 2) and the height is (base + 1), giving ((base + 1) * base) / 2.

However, my base is your n-1, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.

How to show what a commit did?

The answers by Bomber and Jakub (Thanks!) are correct and work for me in different situations.

For a quick glance at what was in the commit, I use

git show <replace this with your commit-id>

But I like to view a graphical Diff when studying something in detail and have set up a P4diff as my git diff and then use

git diff <replace this with your commit-id>^!

Is it possible to use a div as content for Twitter's Popover

Why so complicated? just put this :

data-html='true'

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

Eslint: How to disable "unexpected console statement" in Node.js?

in my vue project i fixed this problem like this :

vim package.json
...
"rules": {
    "no-console": "off"
},
...

ps : package.json is a configfile in the vue project dir, finally the content shown like this:

{
  "name": "metadata-front",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "vue": "^2.5.17",
    "vue-router": "^3.0.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.0.4",
    "@vue/cli-plugin-eslint": "^3.0.4",
    "@vue/cli-service": "^3.0.4",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.8.0",
    "eslint-plugin-vue": "^5.0.0-0",
    "vue-template-compiler": "^2.5.17"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {
        "no-console": "off"
    },
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\. However, they were never registered in the GAC.

I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies to C:\windows\assembly and the application worked on that problem machine. You could also do this programmatically with Gacutil.

So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!

How do I open a new window using jQuery?

This works:

myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

How to center a (background) image within a div?

This works for me :

<style>
   .WidgetBody
        {   
            background: #F0F0F0;
            background-image:url('images/mini-loader.gif');
            background-position: 50% 50%;            
            background-repeat:no-repeat;            
        }
</style>        

Tainted canvases may not be exported

In my case I was drawing onto a canvas tag from a video. To address the tainted canvas error I had to do two things:

<video id="video_source" crossorigin="anonymous">
    <source src="http://crossdomain.example.com/myfile.mp4">
</video>
  • Ensure Access-Control-Allow-Origin header is set in the video source response (proper setup of crossdomain.example.com)
  • Set the video tag to have crossorigin="anonymous"

android.widget.Switch - on/off event listener?

there are two ways,

  1. using xml onclick view Add Switch in XML as below:

    <Switch
    android:id="@+id/switch1"
    android:onClick="toggle"/>
    

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; //outside oncreate
    toggle =(Switch) findViewById(R.id.switch1); // inside oncreate

    public void toggle(View view) //outside oncreate
    {
        if( toggle.isChecked() ){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                start.setBackgroundColor(getColor(R.color.gold));
                stop.setBackgroundColor(getColor(R.color.white));
            }
        }
        else
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                stop.setBackgroundColor(getColor(R.color.gold));
                start.setBackgroundColor(getColor(R.color.white));
            }
        }
    }
  1. using on click listener

Add Switch in XML as below:

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; // outside oncreate
    toggle =(Switch) findViewById(R.id.switch1);  // inside oncreate


    toggle.setOnClickListener(new View.OnClickListener() {   // inside oncreate
        @Override
        public void onClick(View view) {

            if( toggle.isChecked() ){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    start.setBackgroundColor(getColor(R.color.gold));
                }
            }
            else
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    stop.setBackgroundColor(getColor(R.color.gold));
                }
            }

        }

    });

Building a complete online payment gateway like Paypal

Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).

However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.

Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.

Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

Change Orientation of Bluestack : portrait/landscape mode

You could also change resolution of your bluestacks emulator. For example from 800x1280 to 1280x800

Here are instructions for how to change the screen resolution.

To change screen resolution in BlueStacks Android emulator you need to edit two registry items:

  1. Run regedit.exe

  2. Set new resolution (in decimal):

HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Height

and

HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Width

Kill all BlueStacks processes.

Restart BlueStacks

How to update an object in a List<> in C#

You can do somthing like :

if (product != null) {
    var products = Repository.Products;
    var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
    Repository.Products[indexOf] = product;
    // or 
    Repository.Products[indexOf].prop = product.prop;
}

How to break out of while loop in Python?

What I would do is run the loop until the ans is Q

ans=(R)
while not ans=='Q':
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore

How to replace item in array?

Use indexOf to find an element.

var i = items.indexOf(3452);
items[i] = 1010;

How can foreign key constraints be temporarily disabled using T-SQL?

http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx

-- Disable all table constraints

ALTER TABLE MyTable NOCHECK CONSTRAINT ALL

-- Enable all table constraints

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT ALL

-- Disable single constraint

ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint

-- Enable single constraint

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

For a PHP-specific you could try PHPWord - this library is written in pure PHP and provides a set of classes to write to and read from different document file formats (including .doc and .docx). The main drawback is that the quality of converted files can be quite variable.

Alternatively if you want a higher quality option you could use a file conversion API like Zamzar. You can use it to convert a wide range of office formats (and others) into PDF, and you can call from any platform (Windows, Linux, OS X etc).

PHP code to convert a file would look like this:

<?php
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "API_KEY";
$sourceFilePath = "/my.doc"; // Or docx/xls/xlsx etc
$targetFormat = "pdf";

$postData = array(
  "source_file" => $sourceFile,
  "target_format" => $targetFormat
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);

$response = json_decode($body, true);
print_r($response);
?>

Full disclosure: I'm the lead developer for the Zamzar API.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

What about just getting a listing of the tarball and throw away the output, rather than decompressing the file?

tar -tzf my_tar.tar.gz >/dev/null

Edited as per comment. Thanks zrajm!

Edit as per comment. Thanks Frozen Flame! This test in no way implies integrity of the data. Because it was designed as a tape archival utility most implementations of tar will allow multiple copies of the same file!

How do I install a custom font on an HTML site

You can use @font-face in most modern browsers.

Here's some articles on how it works:

Here is a good syntax for adding the font to your app:

Here are a couple of places to convert fonts for use with @font-face:

Also cufon will work if you don't want to use font-face, and it has good documentation on the web site:

Difference between res.send and res.json in Express.js

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the send method doesn't have:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

throw checked Exceptions from mocks with Mockito

Check the Java API for List.
The get(int index) method is declared to throw only the IndexOutOfBoundException which extends RuntimeException.
You are trying to tell Mockito to throw an exception SomeException() that is not valid to be thrown by that particular method call.

To clarify further.
The List interface does not provide for a checked Exception to be thrown from the get(int index) method and that is why Mockito is failing.
When you create the mocked List, Mockito will use the definition of List.class to creates its mock.

The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List API, because get(int index) method does not throw SomeException() so Mockito fails.

If you really want to do this, then have Mockito throw a new RuntimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.

Find the IP address of the client in an SSH session

Simplest command to get the last 10 users logged in to the machine is last|head. To get all the users, simply use last command

How to compile and run C in sublime text 3?

try to write a shell script named run.sh in your project foler

#!/bin/bash
./YOUR_EXECUTIVE_FILE
...AND OTHER THING

and make a Build System to compile and execute it:

{
      "shell_cmd": "make all && ./run.sh"
}

don't forget $chmod +x run.sh

do one thing and do it well:)

Load HTML page dynamically into div with jQuery

I think this would do it:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){

         $(".divlink").click(function(){
         $("#content").attr("src" , $(this).attr("ref"));

});

});
</script>
</head>
<body>
<iframe id="content"></iframe>

<a href="#" ref="page1.html" class="divlink" >Page 1</a><br />
<a href="#" ref="page2.html" class="divlink" >Page 2</a><br />
<a href="#" ref="page3.html" class="divlink" >Page 3</a><br />
<a href="#" ref="page4.html" class="divlink" >Page 4</a><br />
<a href="#" ref="page5.html" class="divlink" >Page 5</a><br />
<a href="#" ref="page6.html" class="divlink" >Page 6</a><br />
</body>
</html>

By the way if you can avoid Jquery, you can just use the target attribute of <a> element:

<html>
<body>
<iframe id="content" name="content"></iframe>

<a href="page1.html" target="content" >Page 1</a><br />
<a href="page2.html" target="content" >Page 2</a><br />
<a href="page3.html" target="content" >Page 3</a><br />
<a href="page4.html" target="content" >Page 4</a><br />
<a href="page5.html" target="content" >Page 5</a><br />
<a href="page6.html" target="content" >Page 6</a><br />
</body>
</html> 

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to specify new GCC path for CMake

Do not overwrite CMAKE_C_COMPILER, but export CC (and CXX) before calling cmake:

export CC=/usr/local/bin/gcc
export CXX=/usr/local/bin/g++
cmake /path/to/your/project
make

The export only needs to be done once, the first time you configure the project, then those values will be read from the CMake cache.


UPDATE: longer explanation on why not overriding CMAKE_C(XX)_COMPILER after Jake's comment

I recommend against overriding the CMAKE_C(XX)_COMPILER value for two main reasons: because it won't play well with CMake's cache and because it breaks compiler checks and tooling detection.

When using the set command, you have three options:

  • without cache, to create a normal variable
  • with cache, to create a cached variable
  • force cache, to always force the cache value when configuring

Let's see what happens for the three possible calls to set:

Without cache

set(CMAKE_C_COMPILER /usr/bin/clang)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)

When doing this, you create a "normal" variable CMAKE_C(XX)_COMPILER that hides the cache variable of the same name. That means your compiler is now hard-coded in your build script and you cannot give it a custom value. This will be a problem if you have multiple build environments with different compilers. You could just update your script each time you want to use a different compiler, but that removes the value of using CMake in the first place.

Ok, then, let's update the cache...

With cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "")
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "")

This version will just "not work". The CMAKE_C(XX)_COMPILER variable is already in the cache, so it won't get updated unless you force it.

Ah... let's use the force, then...

Force cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "" FORCE)
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "" FORCE)

This is almost the same as the "normal" variable version, the only difference is your value will be set in the cache, so users can see it. But any change will be overwritten by the set command.

Breaking compiler checks and tooling

Early in the configuration process, CMake performs checks on the compiler: Does it work? Is it able to produce executables? etc. It also uses the compiler to detect related tools, like ar and ranlib. When you override the compiler value in a script, it's "too late", all checks and detections are already done.

For instance, on my machine with gcc as default compiler, when using the set command to /usr/bin/clang, ar is set to /usr/bin/gcc-ar-7. When using an export before running CMake it is set to /usr/lib/llvm-3.8/bin/llvm-ar.

getContext is not a function

Alternatively you can use:

this.element=$(id)[0];

'mvn' is not recognized as an internal or external command, operable program or batch file

After setting the path with the Maven bin location close the prompt window and restart it. Use the echo %path% command to make sure the path is set with Maven variables then run the command mvn -version. Somehow if the path is set when the prompt window is running it does not pick the new variables.

jQuery - selecting elements from inside a element

Actually, $('#id', this); would select #id at any descendant level, not just the immediate child. Try this instead:

$(this).children('#id');

or

$("#foo > #moo")

or

$("#foo > span")

database vs. flat files

What types of files is not mentioned. If they're media files, go ahead with flat files. You probably just need a DB for tags and some way to associate the "external BLOBs" to the records in the DB. But if full text search is something you need, there's no other way to go but migrate to a full DB.

Another thing, your filesystem might provide the ceiling as far as number of physical files are concerned.

How to hide the title bar for an Activity in XML with existing custom theme

I am using Android Xamarin and this worked for me.

SupportActionBar.Hide();
SetContentView(Resource.Layout.activity_main);

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

How to stop asynctask thread in android?

The reason why things aren't stopping for you is because the process (doInBackground()) runs until it is finished. Therefore you should check if the thread is cancelled or not before doing stuff:

if(!isCancelled()){
// Do your stuff
}

So basically, if the thread is not cancelled, do it, otherwise skip it :) Could be useful to check for this some times during your operation, especially before time taking stuff.

Also it could be useful to "clean up" alittle in

onCancelled();

Documentation for AsyncTask:

http://developer.android.com/reference/android/os/AsyncTask.html

Hope this helps!

$(this).attr("id") not working

your using this in a function, when you should be using the parameter.

You only use $(this) in callbacks... from selections like

$('a').click(function() {
   alert($(this).href);
})

In closing, the proper way (using your code example) would be to do this

obj.attr('id');

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

htaccess Access-Control-Allow-Origin

from my experience;

if it doesn't work from within php do this in .htaccess it worked for me

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin http://www.vknyvz.com  
    Header set Access-Control-Allow-Credentials true
</IfModule>
  • credentials can be true or false depending on your ajax request params

Get custom product attributes in Woocommerce

woocommerce_get_product_terms() is now deprecated.

Use wc_get_product_terms() instead.

Example:

global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );

Rollback to last git commit

Caveat Emptor - Destructive commands ahead.

Mitigation - git reflog can save you if you need it.


1) UNDO local file changes and KEEP your last commit

git reset --hard

2) UNDO local file changes and REMOVE your last commit

git reset --hard HEAD^

3) KEEP local file changes and REMOVE your last commit

git reset --soft HEAD^

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

Difference between Console.Read() and Console.ReadLine()?

Difference between Read(),Readline() and ReadKey() in C#

Read()-Accept the string value and return the string value. Readline() -Accept the string and return Integer ReadKey() -Accept the character and return Character

Summary:

1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Read the user and password in Application -> Advance Settings for Cental Admin application will work.

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

Oracle SQL Developer - tables cannot be seen

grant select on sys.external_tab$ to [myUser]; worked for me. thanx Codo

How to draw a line in android

Simple one

 <TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#c0c0c0"
    android:id="@+id/your_id"
    android:layout_marginTop="160dp" />

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

How to display image from database using php

Simply replace

print $image;

with

 echo '<img src=".$image." >';

Why should C++ programmers minimize use of 'new'?

I think the poster meant to say You do not have to allocate everything on theheap rather than the the stack.

Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.

Failed binder transaction when putting an bitmap dynamically in a widget

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.

refer this link

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

tmux set -g mouse-mode on doesn't work

As @Graham42 said, from version 2.1 mouse options has been renamed but you can use the mouse with any version of tmux adding this to your ~/.tmux.conf:

Bash shells:

is_pre_2_1="[[ $(tmux -V | cut -d' ' -f2) < 2.1 ]] && echo true || echo false"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Sh (Bourne shell) shells:

is_pre_2_1="tmux -V | cut -d' ' -f2 | awk '{print ($0 < 2.1) ? "true" : "false"}'"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Hope this helps

How do I get LaTeX to hyphenate a word that contains a dash?

To avoid hyphenation in already hyphenated word I used non-breaking space ~ in combination with backward space \!. For example, command

3~\!\!\!\!-~\!\!\!D

used in the text, suppress hyphenation in word 3-D. Probably not the best solution, but it worked for me!

Redirect stdout to a file in Python?

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

What's the difference between ".equals" and "=="?

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

How to add a "open git-bash here..." context menu to the windows explorer?

What worked for me was almost this, but with the following REGEDIT path:
HKEY_LOCAL_MACHINE/SOFTWARE/Classes/Directory/background/shell and here I created the key Bash, with the value of what I want the display name to be, and then created another key under this named command with the value as the path to git-bash.exe

I'm on Windows 10 and have a fresh git install that didn't add this automatically for some reason (git version 2.12.0 64bit)

Get child Node of another Node, given node name

If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

How can I selectively escape percent (%) in Python strings?

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

Number prime test in JavaScript

I would do it like this:

const isPrime = (num) => num < 10 ? [2, 3, 5, 7].includes(num) : ![2, 3, 5, 7].some(i => !(num % i));

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

Get Environment Variable from Docker Container

This command inspects docker stack processes' environment in the host :

pidof   dockerd containerd containerd-shim | tr ' ' '\n' \
      | xargs -L1 -I{} -- sudo xargs -a '/proc/{}/environ' -L1 -0

PHP function to make slug (URL string)

This may be a way to do it too. Inspired from these links Experts-exchange and alinalexander

function slugifier($txt){

   /* Get rid of accented characters */
   $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
   $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
   $txt = str_replace($search, $replace, $txt);

   /* Lowercase all the characters */
   $txt = strtolower($txt);

   /* Avoid whitespace at the beginning and the ending */
   $txt = trim($txt);

   /* Replace all the characters that are not in a-z or 0-9 by a hyphen */
   $txt = preg_replace("/[^a-z0-9]/", "-", $txt);
   /* Remove hyphen anywhere it's more than one */
   $txt = preg_replace("/[\-]+/", '-', $txt);
   return $txt;   
}

Detecting when a div's height changes using jQuery

In response to user007:

If the height of your element is changing due to items being appended to it using .append() you shouldn't need to detect the change in height. Simply add the reposition of your second element in the same function where you are appending the new content to your first element.

As in:

Working Example

$('.class1').click(function () {
    $('.class1').append("<div class='newClass'><h1>This is some content</h1></div>");
    $('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());
});

Copy array items into another array

instead of push() function use concat function for IE. example,

var a=a.concat(a,new Array('amin'));

How can I clear the input text after clicking

I am supposing you are trying to create a effect, where the textbox contains a label. And when the user click in the textbox, it disappears and lets the user input the text. You do not require Jquery for this.

<input type="text" value="Input Text" onfocus="this.value=''" onblur="(this.value=='')? this.value='Input Text':this.value;" />

Demo

php how to go one level up on dirname(__FILE__)

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

Can Selenium WebDriver open browser windows silently in the background?

I suggest using PhantomJS. For more information, you may visit the Phantom Official Website.

As far as I know PhantomJS works only with Firefox...

After downloading PhantomJs.exe you need to import it to your project as you can see in the picture below PhantomJS.

I have placed mine inside: common ? Library ? phantomjs.exe

Enter image description here

Now all you have to do inside your Selenium code is to change the line

browser = webdriver.Firefox()

To something like

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)

The path to PhantomJS may be different... change as you like :)

This hack worked for me, and I'm pretty sure it will work for u too ;)

Twitter Bootstrap carousel different height images cause bouncing arrows

This jQuery function worked best for me. I'm using bootstrap 4 within a WordPress theme and I've used the full jQuery instead of jQuery slim.

// Set all carousel items to the same height
function carouselNormalization() {

    window.heights = [], //create empty array to store height values
    window.tallest; //create variable to make note of the tallest slide

    function normalizeHeights() {
        jQuery('#latest-blog-posts .carousel-item').each(function() { //add heights to array
            window.heights.push(jQuery(this).outerHeight());
        });
        window.tallest = Math.max.apply(null, window.heights); //cache largest value
        jQuery('#latest-blog-posts .carousel-item').each(function() {
            jQuery(this).css('min-height',tallest + 'px');
        });
    }
    normalizeHeights();

    jQuery(window).on('resize orientationchange', function () {

        window.tallest = 0, window.heights.length = 0; //reset vars
        jQuery('.sc_slides .item').each(function() {
            jQuery(this).css('min-height','0'); //reset min-height
        }); 

        normalizeHeights(); //run it again 

    });

}

jQuery( document ).ready(function() {
    carouselNormalization();
});

Source:

https://gist.github.com/mbacon40/eff3015fe96582806da5

How to list all databases in the mongo shell?

For database list:

show databases
show dbs

For table/collection list:

show collections
show tables
db.getCollectionNames()

How to remove all ListBox items?

Write the following code in the .cs file:

ListBox.Items.Clear();

python dictionary sorting in descending order based on values

you can make use of the below code for sorting in descending order and storing to a dictionary:

        listname = []  
        for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):  
            diction= {"value":value, "key":key}  
            listname.append(diction)

VS Code - Search for text in all files in a directory

Select your folder, Press ? + ? + F Don't know about windows but this works for mac :)

Why do we need virtual functions in C++?

The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

Shape *shape = new Triangle(); 
cout << shape->getName();

In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

  1. C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.
  2. To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.

installation app blocked by play protect

There are three options to get rid of this warning:

  1. You need to disable Play Protect in Play Store -> Play Protect -> Settings Icon -> Scan Device for security threats
  2. Publish app at Google Play Store
  3. Submit an Appeal to the Play Protect.

Changing Jenkins build number

By using environmental variables:

$BUILD_NUMBER =4

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

UIScrollView scroll to bottom programmatically

While Matt solution seems correct to me you need to take in account also the collection view inset if there is one that has been set-up.

The adapted code will be:

CGSize csz = sv.contentSize;
CGSize bsz = sv.bounds.size;
NSInteger bottomInset = sv.contentInset.bottom;
if (sv.contentOffset.y + bsz.height + bottomInset > csz.height) {
    [sv setContentOffset:CGPointMake(sv.contentOffset.x, 
                                     csz.height - bsz.height + bottomInset) 
                animated:YES];
}

Failed to load c++ bson extension

I finally corrected this error by updating my mongodb dependency version to ~2.0.36 in package.json.

 "dependencies": {
    "consolidate": "~0.9.1",
    "express": "3.x",
    "mongodb": "~2.0.36",
    "mongoose": "^4.1.12"
  }

When does System.gc() do something?

System.gc() is implemented by the VM, and what it does is implementation specific. The implementer could simply return and do nothing, for instance.

As for when to issue a manual collect, the only time when you may want to do this is when you abandon a large collection containing loads of smaller collections--a Map<String,<LinkedList>> for instance--and you want to try and take the perf hit then and there, but for the most part, you shouldn't worry about it. The GC knows better than you--sadly--most of the time.

How to clear memory to prevent "out of memory error" in excel vba?

Answer is you can't explicitly but you should be freeing memory in your routines.

Some tips though to help memory

  • Make sure you set object to null before exiting your routine.
  • Ensure you call Close on objects if they require it.
  • Don't use global variables unless absolutely necessary

I would recommend checking the memory usage after performing the routine again and again you may have a memory leak.

git pull from master into the development branch

Scenario:

I have master updating and my branch updating, I want my branch to keep track of master with rebasing, to keep all history tracked properly, let's call my branch Mybranch

Solution:

git checkout master    
git pull --rebase    
git checkout Mybranch    
git rebase master
git push -f origin Mybranch
  • need to resolve all conflicts with git mergetool &, git rebase --continue, git rebase --skip, git add -u, according to situation and git hints, till all is solved

(correction to last stage, in courtesy of Tzachi Cohen, using "-f" forces git to "update history" at server)

now branch should be aligned with master and rebased, also with remote updated, so at git log there are no "behind" or "ahead", just need to remove all local conflict *.orig files to keep folder "clean"

How can I convert JSON to CSV?

This is a modification of @MikeRepass's answer. This version writes the CSV to a file, and works for both Python 2 and Python 3.

import csv,json
input_file="data.json"
output_file="data.csv"
with open(input_file) as f:
    content=json.load(f)
try:
    context=open(output_file,'w',newline='') # Python 3
except TypeError:
    context=open(output_file,'wb') # Python 2
with context as file:
    writer=csv.writer(file)
    writer.writerow(content[0].keys()) # header row
    for row in content:
        writer.writerow(row.values())

Install IPA with iTunes 12

Edit: See Jayprakash Dubey's answer for iTunes 12.7


From the menu shown in the following screenshot, choose Apps. You can drag and drop you IPA file in the next view.

enter image description here

After that, go to your device's page, you'll see the list of apps, install your app and press Apply from the bottom bar.

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

linking jquery in html

In this case, your test.js will not run, because you're loading it before jQuery. put it after jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="test.js"></script>

How to tell if browser/tab is active

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

$dom->@loadHTML($html);

This is incorrect, use this instead:

@$dom->loadHTML($html);

How to use localization in C#

In addition to @Eric Bole-Feysot answer:

Thanks to satellite assemblies, localization can be created based on .dll/.exe files. This way:

  • source code (VS project) could be separated from language project,
  • adding a new language does not require recompiling the project,
  • translation could be made even by the end-user.

There is a little known tool called LSACreator (free for non-commercial use or buy option) which allows you to create localization based on .dll/.exe files. In fact, internally (in language project's directory) it creates/manages localized versions of resx files and compiles an assembly in similar way as @Eric Bole-Feysot described.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).

Thus, it was failing as "Not allowed", since there was no method with POST type on my end.

Changing @GET to @POST above my WS method fixed the issue.

VMware Workstation and Device/Credential Guard are not compatible

Device/Credential Guard is a Hyper-V based Virtual Machine/Virtual Secure Mode that hosts a secure kernel to make Windows 10 much more secure.

enter image description here

...the VSM instance is segregated from the normal operating system functions and is protected by attempts to read information in that mode. The protections are hardware assisted, since the hypervisor is requesting the hardware treat those memory pages differently. This is the same way to two virtual machines on the same host cannot interact with each other; their memory is independent and hardware regulated to ensure each VM can only access it’s own data.

From here, we now have a protected mode where we can run security sensitive operations. At the time of writing, we support three capabilities that can reside here: the Local Security Authority (LSA), and Code Integrity control functions in the form of Kernel Mode Code Integrity (KMCI) and the hypervisor code integrity control itself, which is called Hypervisor Code Integrity (HVCI).

enter image description here

When these capabilities are handled by Trustlets in VSM, the Host OS simply communicates with them through standard channels and capabilities inside of the OS. While this Trustlet-specific communication is allowed, having malicious code or users in the Host OS attempt to read or manipulate the data in VSM will be significantly harder than on a system without this configured, providing the security benefit.

Running LSA in VSM, causes the LSA process itself (LSASS) to remain in the Host OS, and a special, additional instance of LSA (called LSAIso – which stands for LSA Isolated) is created. This is to allow all of the standard calls to LSA to still succeed, offering excellent legacy and backwards compatibility, even for services or capabilities that require direct communication with LSA. In this respect, you can think of the remaining LSA instance in the Host OS as a ‘proxy’ or ‘stub’ instance that simply communicates with the isolated version in prescribed ways.


And Hyper-V and VMware didn't work the same time until 2020, when VMware used Hyper-V Platform to co-exist with Hyper-V starting with Version 15.5.5.

How does VMware Workstation work before version 15.5.5?

VMware Workstation traditionally has used a Virtual Machine Monitor (VMM) which operates in privileged mode requiring direct access to the CPU as well as access to the CPU’s built in virtualization support (Intel’s VT-x and AMD’s AMD-V). When a Windows host enables Virtualization Based Security (“VBS“) features, Windows adds a hypervisor layer based on Hyper-V between the hardware and Windows. Any attempt to run VMware’s traditional VMM fails because being inside Hyper-V the VMM no longer has access to the hardware’s virtualization support.

Introducing User Level Monitor

To fix this Hyper-V/Host VBS compatibility issue, VMware’s platform team re-architected VMware’s Hypervisor to use Microsoft’s WHP APIs. This means changing our VMM to run at user level instead of in privileged mode, as well modifying it to use the WHP APIs to manage the execution of a guest instead of using the underlying hardware directly.

What does this mean to you?

VMware Workstation/Player can now run when Hyper-V is enabled. You no longer have to choose between running VMware Workstation and Windows features like WSL, Device Guard and Credential Guard. When Hyper-V is enabled, ULM mode will automatically be used so you can run VMware Workstation normally. If you don’t use Hyper-V at all, VMware Workstation is smart enough to detect this and the VMM will be used.

System Requirements

To run Workstation/Player using the Windows Hypervisor APIs, the minimum required Windows 10 version is Windows 10 20H1 build 19041.264. VMware Workstation/Player minimum version is 15.5.5.

To avoid the error, update your Windows 10 to Version 2004/Build 19041 (Mai 2020 Update) and use at least VMware 15.5.5.

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

How to sort an array of integers correctly

The reason why the sort function behaves so weird

From the documentation:

[...] the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

If you print the unicode point values of the array then it will get clear.

_x000D_
_x000D_
console.log("140000".charCodeAt(0));_x000D_
console.log("104".charCodeAt(0));_x000D_
console.log("99".charCodeAt(0));_x000D_
_x000D_
//Note that we only look at the first index of the number "charCodeAt(  0  )"
_x000D_
_x000D_
_x000D_

This returns: "49, 49, 57".

49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)

Now, because 140000 and 104 returned the same values (49) it cuts the first index and checks again:

_x000D_
_x000D_
console.log("40000".charCodeAt(0));_x000D_
console.log("04".charCodeAt(0));_x000D_
_x000D_
//Note that we only look at the first index of the number "charCodeAt(  0  )"
_x000D_
_x000D_
_x000D_

52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)

If we sort this, then we will get:

40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)

so 104 comes before 140000.

So the final result will be:

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
numArray = numArray.sort();_x000D_
console.log(numArray)
_x000D_
_x000D_
_x000D_

104, 140000, 99

Conclusion:

sort() does sorting by only looking at the first index of the numbers. sort() does not care if a whole number is bigger than another, it compares the value of the unicode of the digits, and if there are two equal unicode values, then it checks if there is a next digit and compares it as well.

To sort correctly, you have to pass a compare function to sort() like explained here.

How can I get the current class of a div with jQuery?

$('#div1').attr('class')

will return a string of the classes. Turn it into an array of class names

var classNames = $('#div1').attr('class').split(' ');

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

Does java have a int.tryparse that doesn't throw an exception for bad data?

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

How to check if a file exists in the Documents directory in Swift?

Swift 4.2

extension URL    {
    func checkFileExist() -> Bool {
        let path = self.path
        if (FileManager.default.fileExists(atPath: path))   {
            print("FILE AVAILABLE")
            return true
        }else        {
            print("FILE NOT AVAILABLE")
            return false;
        }
    }
}

Using: -

if fileUrl.checkFileExist()
   {
      // Do Something
   }

Returning a value from thread?

The BackgroundWorker is nice when developing for Windows Forms.

Say you wanted to pass a simple class back and forth:

class Anything {
    // Number and Text are for instructional purposes only
    public int Number { get; set; }
    public string Text { get; set; }
    // Data can be any object - even another class
    public object Data { get; set; }
}

I wrote up a short class that does the following:

  • Create or Clear a list
  • Start a loop
  • In loop, create a new item for the list
  • In loop, create a thread
  • In loop, send the item as a parameter to the thread
  • In loop, start the thread
  • In loop, add thread to list to watch
  • After loop, join each thread
  • After all joins have completed, display the results

From inside the thread routine:

  • Call lock so that only 1 thread can enter this routine at a time (others have to wait)
  • Post information about the item.
  • Modify the item.
  • When the thread completes, the data is displayed on the console.

Adding a delegate can be useful for posting your data directly back to your main thread, but you may need to use Invoke if some of the data items are not thread safe.

class AnyTask {

    private object m_lock;

    public AnyTask() {
        m_lock = new object();
    }
    // Something to use the delegate
    public event MainDelegate OnUpdate;

    public void Test_Function(int count) {
        var list = new List<Thread>(count);
        for (var i = 0; i < count; i++) {
            var thread = new Thread(new ParameterizedThreadStart(Thread_Task));
            var item = new Anything() {
                Number = i,
                Text = String.Format("Test_Function #{0}", i)
            };
            thread.Start(item);
            list.Add(thread);
        }
        foreach (var thread in list) {
            thread.Join();
        }
    }

    private void MainUpdate(Anything item, bool original) {
        if (OnUpdate != null) {
            OnUpdate(item, original);
        }
    }

    private void Thread_Task(object parameter) {
        lock (m_lock) {
            var item = (Anything)parameter;
            MainUpdate(item, true);
            item.Text = String.Format("{0}; Thread_Task #{1}", item.Text, item.Number);
            item.Number = 0;
            MainUpdate(item, false);
        }
    }

}

To test this, create a little Console Application, and put this in the Program.cs file:

// A delegate makes life simpler
delegate void MainDelegate(Anything sender, bool original);

class Program {

    private const int COUNT = 15;
    private static List<Anything> m_list;

    static void Main(string[] args) {
        m_list = new List<Anything>(COUNT);
        var obj = new AnyTask();
        obj.OnUpdate += new MainDelegate(ThreadMessages);
        obj.Test_Function(COUNT);
        Console.WriteLine();
        foreach (var item in m_list) {
            Console.WriteLine("[Complete]:" + item.Text);
        }
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static void ThreadMessages(Anything item, bool original) {
        if (original) {
            Console.WriteLine("[main method]:" + item.Text);
        } else {
            m_list.Add(item);
        }
    }

}

Here is a screenshot of what I got with this:

Console Output

I hope others can understand what I've tried to explain.

I enjoy working on threads and using delegates. They make C# a lot of fun.

Appendix: For VB Coders

I wanted to see what was involved in writing the code above as a VB Console Application. The conversion involved a few things I didn't expect, so I will update this thread here for those wanting to know how to thread in VB.

Imports System.Threading

Delegate Sub MainDelegate(sender As Anything, original As Boolean)

Class Main

    Private Const COUNT As Integer = 15
    Private Shared m_list As List(Of Anything)

    Public Shared Sub Main(args As String())
        m_list = New List(Of Anything)(COUNT)
        Dim obj As New AnyTask()
        AddHandler obj.OnUpdate, New MainDelegate(AddressOf ThreadMessages)
        obj.Test_Function(COUNT)
        Console.WriteLine()
        For Each item As Anything In m_list
            Console.WriteLine("[Complete]:" + item.Text)
        Next
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub

    Private Shared Sub ThreadMessages(item As Anything, original As Boolean)
        If original Then
            Console.WriteLine("[main method]:" + item.Text)
        Else
            m_list.Add(item)
        End If
    End Sub

End Class

Class AnyTask

    Private m_lock As Object

    Public Sub New()
        m_lock = New Object()
    End Sub
    ' Something to use the delegate
    Public Event OnUpdate As MainDelegate

    Public Sub Test_Function(count As Integer)
        Dim list As New List(Of Thread)(count)
        For i As Int32 = 0 To count - 1
            Dim thread As New Thread(New ParameterizedThreadStart(AddressOf Thread_Task))
            Dim item As New Anything()
            item.Number = i
            item.Text = String.Format("Test_Function #{0}", i)
            thread.Start(item)
            list.Add(thread)
        Next
        For Each thread As Thread In list
            thread.Join()
        Next
    End Sub

    Private Sub MainUpdate(item As Anything, original As Boolean)
        RaiseEvent OnUpdate(item, original)
    End Sub

    Private Sub Thread_Task(parameter As Object)
        SyncLock m_lock
            Dim item As Anything = DirectCast(parameter, Anything)
            MainUpdate(item, True)
            item.Text = [String].Format("{0}; Thread_Task #{1}", item.Text, item.Number)
            item.Number = 0
            MainUpdate(item, False)
        End SyncLock
    End Sub

End Class


Class Anything
    ' Number and Text are for instructional purposes only
    Public Property Number() As Integer
        Get
            Return m_Number
        End Get
        Set(value As Integer)
            m_Number = value
        End Set
    End Property
    Private m_Number As Integer
    Public Property Text() As String
        Get
            Return m_Text
        End Get
        Set(value As String)
            m_Text = value
        End Set
    End Property
    Private m_Text As String
    ' Data can be anything or another class
    Public Property Data() As Object
        Get
            Return m_Data
        End Get
        Set(value As Object)
            m_Data = value
        End Set
    End Property
    Private m_Data As Object
End Class

How to Apply Gradient to background view of iOS Swift App

Cleaner code that lets you pass any UIColor to an instance of the GradientLayer class:

class GradientLayer {

    let gradientLayer: CAGradientLayer
    let colorTop: CGColor
    let colorBottom: CGColor

    init(colorTop: UIColor, colorBottom: UIColor) {
        self.colorTop = colorTop.CGColor
        self.colorBottom = colorBottom.CGColor
        gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
    }
}

How to add new contacts in android

 private void addContact(String name, String number){
    Uri addContactsUri = ContactsContract.Data.CONTENT_URI;
    long rowContactId = getRawContactId();
    String displayName = name;
    insertContactDisplayName(addContactsUri, rowContactId, displayName);
    String phoneNumber = number;
    String phoneTypeStr = "Mobile";//work,home etc
    insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);
}

private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
    ContentValues contentValues = new ContentValues();

    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);

    // Put contact display name value.
    contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);

    activity.getContentResolver().insert(addContactsUri, contentValues);

}


private long getRawContactId()
{
    // Inser an empty contact.
    ContentValues contentValues = new ContentValues();
    Uri rawContactUri = activity.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
    // Get the newly created contact raw id.
    long ret = ContentUris.parseId(rawContactUri);
    return ret;
}

private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr) {
    // Create a ContentValues object.
    ContentValues contentValues = new ContentValues();

    // Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);

    // Put phone number value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);

    // Calculate phone type by user selection.
    int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;

    if ("home".equalsIgnoreCase(phoneTypeStr)) {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
    } else if ("mobile".equalsIgnoreCase(phoneTypeStr)) {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
    } else if ("work".equalsIgnoreCase(phoneTypeStr)) {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
    }
    // Put phone type value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);

    // Insert new contact data into phone contact list.
    activity.getContentResolver().insert(addContactsUri, contentValues);

}

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In addition to C Johnson list I would add the following point:

Check in Visual Studio:
Project Properties -> Configuration Properties -> Linker -> Command line.

"Additional Options" should NOT contain /machine:X86

I have such key, generated by CMake output: CMake generated x86 project, then I added x64 platform via Configuration Manager in Visual Studio 2010 - everything was created fine for the new platform except that the linker command line, specified /machine:X86 separately.

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Fixing broken UTF-8 encoding

It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.

When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

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

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Sending email through Gmail SMTP server with C#

I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):

<system.net>
  <mailSettings>
    <smtp from="[email protected]" deliveryMethod="Network">
      <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="[email protected]"/>
    </smtp>
  </mailSettings>
</system.net>

You might have to enable POP or IMAP on your Gmail account first: https://mail.google.com/mail/?shva=1#settings/fwdandpop

I recommend trying it with a normal mail client first...

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

How exactly does the python any() function work?

Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Add data dynamically to an Array

There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:

$array = array();

Add to an array:

$array[] = "item"; // for your $arr1 
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");

Remove from an array:

$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);

There are plenty more ways, these are just some examples.

Is the Javascript date object always one day off?

I faced some issue like this. But my issue was the off set while getting date from database.

this is stroed in the database and it is in the UTC format.

2019-03-29 19:00:00.0000000 +00:00

So when i get from database and check date it is adding offset with it and send back to javascript.

enter image description here

It is adding +05:00 because this is my server timezone. My client is on different time zone +07:00.

2019-03-28T19:00:00+05:00 // this is what i get in javascript.

So here is my solution what i do with this issue.

var dates = price.deliveryDate.split(/-|T|:/);
var expDate = new Date(dates[0], dates[1] - 1, dates[2], dates[3], dates[4]);
var expirationDate = new Date(expDate);

So when date come from the server and have server offset so i split date and remove server offset and then convert to date. It resolves my issue.

Creating a select box with a search option

Select2 http://select2.github.io may be even better and more active than Chosen.

See this comparison: http://sitepoint.com/jquery-select-box-components-chosen-vs-select2

I went for Select2 (a few months ago) because Chosen had an issue when using Chinese characters via an IME http://github.com/harvesthq/chosen/issues/2663 It works great.

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Pan & Zoom Image

One addition to the superb solution provided by @Wieslaw Šoltés answer above

The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (child != null)
        {
            var tt = GetTranslateTransform(child);
            start = e.GetPosition(this);
            origin = new Point(tt.X, tt.Y);
            this.Cursor = Cursors.Hand;
            child.CaptureMouse();
        }
    }

With this:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
        {
            if (child != null)
            {
                var tt = GetTranslateTransform(child);
                start = e.GetPosition(this);
                origin = new Point(tt.X, tt.Y);
                this.Cursor = Cursors.Hand;
                child.CaptureMouse();
            }
        }

        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
        {
            this.Reset();
        }
    }