text:
Q: SQL Server - Get a list of datatypes, max length, if its an identity and if its a primary key without object_ID function I need a query that gets the datatype, max length, if its an identity and if its a primary key from a specific table_name without the use of the object_id function. So far what I have right now (and also found this somewhere on stackoverflow):
 SELECT col.COLUMN_NAME AS ColumnName
     , col.DATA_TYPE AS DataType
     , col.CHARACTER_MAXIMUM_LENGTH AS MaxLength
     , COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsIdentity')AS IS_IDENTITY
     , CAST(ISNULL(pk.is_primary_key, 0)AS bit)AS IsPrimaryKey
  FROM INFORMATION_SCHEMA.COLUMNS AS col
       LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA
                      , o.name AS TABLE_NAME
                      , c.name AS COLUMN_NAME
                      , i.is_primary_key
                   FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
                                                                     AND i.index_id = ic.index_id
                                         JOIN sys.objects AS o ON i.object_id = o.object_id
                                         LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
                                                                   AND c.column_id = ic.column_id
                  WHERE i.is_primary_key = 1)AS pk ON col.TABLE_NAME = pk.TABLE_NAME
                                                  AND col.TABLE_SCHEMA = pk.TABLE_SCHEMA
                                                  AND col.COLUMN_NAME = pk.COLUMN_NAME
 WHERE col.TABLE_NAME = 'tbl_users'
 ORDER BY col.TABLE_NAME, col.ORDINAL_POSITION;

Im using this code for a cursor and when I try to get the value of IS_IDENTITY, its always empty or something. I feel like dynamic sql and cursor don't like the OBJECT_ID function. When I run this query without the cursor and stuff, it works perfectly fine.
FULL CODE:
ALTER Procedure [dbo].[sp_generateUpserts]
    @databaseName nvarchar(MAX)
AS
BEGIN

SET NOCOUNT ON

DECLARE @tranState BIT
IF @@TRANCOUNT = 0
BEGIN
    SET @tranState = 1
    BEGIN TRANSACTION tranState
END

BEGIN TRY
    Declare @TABLE_NAME varchar(100)
    Declare @COLUMN_NAME varchar(100)
    Declare @COLUMN_NAME_WITH_SPACE varchar(100)
    Declare @DATA_TYPE varchar(100)
    Declare @CHARACTER_MAXIMUM_LENGTH INT
    Declare @IS_PK INT
    Declare @IS_IDENTITY INT

    DECLARE @statement nvarchar(MAX)
    SET @statement = N'USE [' + @databaseName + '];
    DECLARE cursorUpsert CURSOR FOR
    SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    ORDER BY TABLE_NAME'
    EXECUTE sp_executesql @statement

    DECLARE @use_db nvarchar(max)
    DECLARE @generateSpStatement varchar(MAX)

    DECLARE @spParameters varchar(MAX) = ''
    DECLARE @whereColumns varchar(MAX) = ''
    DECLARE @updateStatement varchar(MAX) = ''
    DECLARE @insertStatement varchar(MAX) = ''
    DECLARE @valueStatement varchar(MAX) = ''

    OPEN cursorUpsert
    FETCH NEXT FROM cursorUpsert
    INTO @TABLE_NAME

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @statementColumns nvarchar(MAX)
        SET @statementColumns = N'USE [' + @databaseName + '];
        DECLARE cursorUpsertColumns CURSOR FOR
        SELECT col.COLUMN_NAME
     , col.DATA_TYPE
     , col.CHARACTER_MAXIMUM_LENGTH
    , COLUMNPROPERTY(OBJECT_ID(QUOTENAME(col.TABLE_SCHEMA) + ''.'' +  QUOTENAME(col.TABLE_NAME)), col.COLUMN_NAME, ''IsIdentity'')AS IS_IDENTITY
     , CAST(ISNULL(pk.is_primary_key, 0) AS bit) AS IS_PK
  FROM INFORMATION_SCHEMA.COLUMNS AS col
       LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA
                      , o.name AS TABLE_NAME
                      , c.name AS COLUMN_NAME
                      , i.is_primary_key
                   FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
                                                                     AND i.index_id = ic.index_id
                                         JOIN sys.objects AS o ON i.object_id = o.object_id
                                         LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
                                                                   AND c.column_id = ic.column_id
                  WHERE i.is_primary_key = 1)AS pk ON col.TABLE_NAME = pk.TABLE_NAME
                                                  AND col.TABLE_SCHEMA = pk.TABLE_SCHEMA
                                                  AND col.COLUMN_NAME = pk.COLUMN_NAME
 WHERE col.TABLE_NAME = ''' + @TABLE_NAME + '''
 ORDER BY col.TABLE_NAME, col.ORDINAL_POSITION;'
        EXECUTE sp_executesql @statementColumns

        OPEN cursorUpsertColumns
        FETCH NEXT FROM cursorUpsertColumns
        INTO @COLUMN_NAME, @DATA_TYPE, @CHARACTER_MAXIMUM_LENGTH, @IS_IDENTITY, @IS_PK

        WHILE @@FETCH_STATUS = 0
        BEGIN
            -- Parameters for the SP
            IF @COLUMN_NAME LIKE '% %'
            BEGIN
                SET @COLUMN_NAME_WITH_SPACE = @COLUMN_NAME
                SET @COLUMN_NAME_WITH_SPACE = REPLACE(@COLUMN_NAME_WITH_SPACE,' ','_')
                SET @spParameters = @spParameters + CHAR(13) + '@' + @COLUMN_NAME_WITH_SPACE + ' ' + @DATA_TYPE
            END
            ELSE
            BEGIN
                SET @spParameters = @spParameters + CHAR(13) + '@' + @COLUMN_NAME + ' ' + @DATA_TYPE
            END

            IF @DATA_TYPE IN ('varchar', 'nvarchar', 'char', 'nchar')
            BEGIN
                IF @CHARACTER_MAXIMUM_LENGTH = '-1'
                    BEGIN
                        SET @spParameters = @spParameters + '(MAX)'
                    END
                ELSE
                    BEGIN
                        SET @spParameters = @spParameters + '(' + CAST(@CHARACTER_MAXIMUM_LENGTH As Varchar(10)) + ')'
                    END
            END
            -- Add a comma after each parameter
            SET @spParameters = @spParameters + ', '

            IF @COLUMN_NAME IN ('top')
            BEGIN
                IF @IS_IDENTITY != 1
                BEGIN
                    print('YES IDENTITY')
                END
                -- Add where parameters: ColumnName=@ColumnName AND
                SET @whereColumns = @whereColumns + CHAR(32) + '[' + @COLUMN_NAME + ']=@' + @COLUMN_NAME + ' AND'
                -- Add update parameters: column1 = value1, etc.
                IF @IS_IDENTITY != 1 OR @IS_PK != 1
                BEGIN
                    SET @updateStatement = @updateStatement + CHAR(32) + '[' + @COLUMN_NAME + ']=@' + @COLUMN_NAME + ','
                END
                -- Add insert columns
                SET @insertStatement = @insertStatement + CHAR(32) + '[' + @COLUMN_NAME + '],'
                -- Add values
                SET @valueStatement = @valueStatement + CHAR(32) + '@' + @COLUMN_NAME + ','
            END
            ELSE IF @COLUMN_NAME LIKE '% %'
            BEGIN
            IF @IS_IDENTITY != 1
                BEGIN
                    print('YES IDENTITY')
                END
                -- Add where parameters: ColumnName=@ColumnName AND
                SET @whereColumns = @whereColumns + CHAR(32) + '[' + @COLUMN_NAME + ']=@' + @COLUMN_NAME_WITH_SPACE + ' AND'
                -- Add update parameters: column1 = value1, etc.
                IF @IS_IDENTITY != 1 OR @IS_PK != 1
                BEGIN
                    SET @updateStatement = @updateStatement + CHAR(32) + '[' + @COLUMN_NAME + ']=@' + @COLUMN_NAME_WITH_SPACE + ','
                END
                -- Add insert columns
                SET @insertStatement = @insertStatement + CHAR(32) + '['+ @COLUMN_NAME + '],'
                -- Add values
                SET @valueStatement = @valueStatement + CHAR(32) + '@' + @COLUMN_NAME_WITH_SPACE + ','
            END
            ELSE
            BEGIN
            IF @IS_IDENTITY != 1
                BEGIN
                    print('YES IDENTITY')
                END
                -- Add where parameters: ColumnName=@ColumnName AND
                SET @whereColumns = @whereColumns + CHAR(32) + @COLUMN_NAME + '=@' + @COLUMN_NAME + ' AND'
                -- Add update parameters: column1 = value1, etc.
                IF @IS_IDENTITY != 1 OR @IS_PK != 1
                BEGIN
                    SET @updateStatement = @updateStatement + CHAR(32) + @COLUMN_NAME + '=@' + @COLUMN_NAME + ','
                END
                -- Add insert columns
                SET @insertStatement = @insertStatement + CHAR(32) + @COLUMN_NAME + ','
                -- Add values
                SET @valueStatement = @valueStatement + CHAR(32) + '@' + @COLUMN_NAME + ','
            END

            FETCH NEXT FROM cursorUpsertColumns
            INTO @COLUMN_NAME, @DATA_TYPE, @CHARACTER_MAXIMUM_LENGTH, @IS_IDENTITY, @IS_PK
            if @@FETCH_STATUS!=0
                begin
                    -- Last row, remove things
                    -- Remove the last AND word
                    SET @whereColumns = left (@whereColumns, len(@whereColumns) -3)
                    -- Remove the last comma from the parameter
                    SET @spParameters = left (@spParameters, len(@spParameters) -1)
                    -- Remove the last comma from the updateStatement
                    SET @updateStatement = left (@updateStatement, len(@updateStatement) -1)
                    -- Remove the last comma from the insertStatement
                    SET @insertStatement = left (@insertStatement, len(@insertStatement) -1)
                    -- Remove the last comma from the valueStatement
                    SET @valueStatement = left (@valueStatement, len(@valueStatement) -1)
                end

        END;
        CLOSE cursorUpsertColumns;
        DEALLOCATE cursorUpsertColumns;
        --- End Cursor Columns

        -- Generate the SP
        SET @generateSpStatement = 'CREATE Procedure [dbo].[sp_' + @TABLE_NAME + '_upsert]' + @spParameters
        SET @generateSpStatement = @generateSpStatement + CHAR(13) + 'AS BEGIN' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'SET NOCOUNT ON' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'DECLARE @tranState BIT' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'IF @@TRANCOUNT = 0' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'BEGIN' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) +'SET @tranState = 1' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) +'set transaction isolation level serializable' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) +'BEGIN TRANSACTION tranState' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'END' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13) + 'BEGIN TRY' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'IF EXISTS(SELECT 1 FROM ' + @TABLE_NAME + ' WITH (updlock) WHERE' + @whereColumns +  ')' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) + 'UPDATE ' + @TABLE_NAME + ' SET' + @updateStatement + ' WHERE ' + @whereColumns + ';' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'ELSE' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) + 'INSERT INTO ' + @TABLE_NAME + ' ('+ @insertStatement + ') VALUES (' + @valueStatement + ');' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'IF @tranState = 1 AND XACT_STATE() = 1' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) + 'COMMIT TRANSACTION tranState' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + 'END TRY' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13) + 'BEGIN CATCH' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'DECLARE @Error_Message VARCHAR(5000)' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'DECLARE @Error_Severity INT' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'DECLARE @Error_State INT' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'SELECT @Error_Message = ERROR_MESSAGE()' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'SELECT @Error_Severity = ERROR_SEVERITY()' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'SELECT @Error_State = ERROR_STATE()' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'IF @tranState = 1 AND XACT_STATE() <> 0' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + CHAR(9) +'ROLLBACK TRANSACTION' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(9) + 'RAISERROR (@Error_Message, @Error_Severity, @Error_State)' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + 'END CATCH' + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + CHAR(13)
        SET @generateSpStatement = @generateSpStatement + 'END' + CHAR(13)

        --print(@generateSpStatement)

        -- Reset Variables
        SET @generateSpStatement = ''
        SET @spParameters = ''
        SET @whereColumns = ''
        SET @updateStatement = ''
        SET @insertStatement = ''
        SET @valueStatement = ''

      FETCH NEXT FROM cursorUpsert
      INTO @TABLE_NAME
    END;

    CLOSE cursorUpsert;
    DEALLOCATE cursorUpsert;

    IF @tranState = 1
        AND XACT_STATE() = 1
        COMMIT TRANSACTION tranState
END TRY
BEGIN CATCH

    DECLARE @Error_Message VARCHAR(5000)
    DECLARE @Error_Severity INT
    DECLARE @Error_State INT

    SELECT @Error_Message = ERROR_MESSAGE()
    SELECT @Error_Severity = ERROR_SEVERITY()
    SELECT @Error_State = ERROR_STATE()

    IF @tranState = 1 AND XACT_STATE() <> 0
        ROLLBACK TRANSACTION

    RAISERROR (@Error_Message, @Error_Severity, @Error_State)

END CATCH
END

A:
I feel like dynamic sql and cursor don't like the OBJECT_ID function.

It has nothing to do with OBJECT_ID but most likely incorrect double qouting when using with dynamic string:
COLUMNPROPERTY(OBJECT_ID(''['' + col.TABLE_SCHEMA + ''].['' + col.TABLE_NAME + '']''), col.COLUMN_NAME, ''IsIdentity'')AS IS_IDENTITY

Anyway you should avoid manually adding [ and use QUOTENAME instead:
COLUMNPROPERTY(OBJECT_ID(QUOTENAME(col.TABLE_SCHEMA) + ''.'' +  QUOTENAME(col.TABLE_NAME)), col.COLUMN_NAME, ''IsIdentity'')AS IS_IDENTITY

It's a common case and it would be really nice if here-strings/text quoting were supported.

A: Another slightly simpler way of getting this information would be something like..
Declare   @Schema SYSNAME = 'dbo'
        , @Table  SYSNAME=  'Orders'

SELECT
      name                  Column_Name
    , system_type_name      Data_Type
    , max_length            Max_Length
    , is_identity_column    Is_Identity_Column
    , ISNULL(c.PK_Column,0) Is_Primary_Key_Column
FROM sys.dm_exec_describe_first_result_set (N'SELECT * FROM '+ @Schema +'.' + @Table, null, 0) r
OUTER APPLY (
                SELECT 1 PK_Column
                FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE s
                WHERE OBJECTPROPERTY(OBJECT_ID(s.CONSTRAINT_SCHEMA + '.' + QUOTENAME(s.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
                AND s.TABLE_NAME = @Table
                AND s.TABLE_SCHEMA = @Schema
                AND r.name COLLATE DATABASE_DEFAULT = s.COLUMN_NAME
            ) c(PK_Column)

You can put this code inside a function and simply call this function cross applying it with sys.tables catalog view.
The dynamic management view sys.dm_exec_describe_first_result_set has lots of other useful information too.
Lets suppose you create a function like this..
CREATE FUNCTION dbo.fn_get_Column_Info (
  @Schema SYSNAME
, @Table  SYSNAME)
RETURNS TABLE
AS
RETURN
(

SELECT
      name                  Column_Name
    , system_type_name      Data_Type
    , max_length            Max_Length
    , is_identity_column    Is_Identity_Column
    , ISNULL(c.PK_Column,0) Is_Primary_Key_Column
FROM sys.dm_exec_describe_first_result_set (N'SELECT * FROM '+ @Schema +'.' + @Table, null, 0) r
OUTER APPLY (
                SELECT 1 PK_Column
                FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE s
                WHERE OBJECTPROPERTY(OBJECT_ID(s.CONSTRAINT_SCHEMA + '.' + QUOTENAME(s.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
                AND s.TABLE_NAME = @Table
                AND s.TABLE_SCHEMA = @Schema
                AND r.name COLLATE DATABASE_DEFAULT = s.COLUMN_NAME
            ) c(PK_Column)
);
GO

Then your query to get all the information you need would be as simple as..
SELECT s.name , t.name,  f.*
FROM sys.schemas s
INNER JOIN sys.Tables t ON s.schema_id = t.schema_id
CROSS APPLY dbo.fn_get_Column_Info(s.name , t.name) f;

No need for any cursor or dynamic SQL, unless you want to do this for all the databases on a server. But even if you had to do that for all databases it would be a much simpler cursor.


text:
Q: Parsing of DateTime with timezone Here is my code:
DateTime dateTime;
string str = "2016-02-11 23:02:30 -0500";
if (!DateTime.TryParse(str, out dateTime))
{

}

I am receiving {2/12/2016 7:02:30 AM} as dateTime result. But I want to get 2/11/2016, is it possible?

A: I think you are looking for TimeZoneInfo:
DateTime dateTime;
string str = "2016-02-11 23:02:30 -0500";
if (!DateTime.TryParse(str, out dateTime))
{
    // error
}

dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);

var serverTimeZone = TimeZoneInfo.Local; // Server time zone
var allTimeZones = TimeZoneInfo.GetSystemTimeZones(); // Time zone list

var clientTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");

// DateTime in server time zone
var dateTimeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, clientTimeZone.Id, serverTimeZone.Id);

Take a look at this fiddle: https://dotnetfiddle.net/Apx51v
Note:
And remember, DateTime doesn't contains time-zone information.

"A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism"
  DateTime in .NET

A: You need to  use DateTimeOffset.Parse() to parse string into DateTimeOffset object with represented offset and than format it to string without it("yyyy-MM-dd HH:mm:ss" in example)

A: Since your string has UTC Offset value, I would parse it to DateTimeOffset instead of DateTime.
DateTimeOffset dto;
string str = "2016-02-11 23:02:30 -0500";
if (DateTimeOffset.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, out dto))
{
   //Success
}

Now you have a DateTimeOffset as {11.02.2016 23:02:30 -05:00} and you can use it's .DateTime property which returns 11.02.2016 23:02:30.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncaught SyntaxError: Unexpected token . AKA how to check for an Id in jQuery I need to know how to check for a CSS Id (or a class) if its enabled or disabled in jQuery. For example, let's say I have two Ids, sectionA and sectionB on some form pointing to two different sections of markup.
Now, I have a common reusable JS function that does some work based on which of the sections was referenced(activated) by the user. Think of user making entries on the some input fields of sectionA or viceversa. So I am trying to do something like this (please pardon my syntax):
function doSomething() {
    if $('#sectionA').Enabled { //I know its not real syntax {
       var inp = document.getElementById('sectionA');
    }
    else if ('#sectionB').Enabled {
       var inp = document.getElementById('sectionB');
    }
}

etc.
Sorry if this is too trivial a question. I know the question is hard to visualize at first but I wish I could draw it out. I certainly appreciate any helpful hints.

A: jQuery selectors us the same syntax as CSS does, so you can just use the :enabled pseudo-class selector:
  if ($('#sectionA:enabled')) { ... }

But, after reading your comments, I'm not sure enabled is what you are looking for. You may want :active, which would be:
  if ($('#sectionA:active')) { ... }

You could also write both of these like this:
  if ($('#sectionA').is(':enabled')) { ... }
  if ($('#sectionA').is(':active')) { ... }

Also, if you are going to use jQuery, why not use it here as well:
  document.getElementById('sectionA')

Can just be:
  $('#sectionA')

A: That's because the code  you  have  provided  has syntax errors like
.       else if ('#sectionB').Enabled

Should be
.       else if ($('#sectionB:enabled'))

Use brackets with if else conditions.. And Check the $ sign there, also .Enabled is nothing in jQuery, if it's a check box then use .prop('checked') or .is(':enabled')


text:
Q: Как создать часы с помощью JavaScript или PHP Вида:
2:37:09 Monday
A:

<form name="F"><input type="button" name="chas" value="XX:XX:XX"></form>

Источник.


text:
Q: C#: ToolStripDropDown doesn't Dispose/DestroyHandle I'm using the ToolStripDropDown to show up an selectionpopup.
The ToolStripDropDown contains a few custom controls with running Threads.
The Threads ends with the OnHandleDestroyed event, but for some reason the ToolStripDropDown doesn't dispose/destroy it's handle after closing.
Disposing the ToolStripDropDown on the closed-event gives me an exception because anything still accesses the ToolStripDropDown.
How do I know if the custom Control is still in use or not to end the thread?
Custom-Control:
public class CControl : Control
{
    Thread StyleThread;
    Object lockOBJ = new Object();
    bool abortthread = false;

    public CControl()
    {
        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
        this.SetStyle(ControlStyles.Selectable, false);

        StyleThread = new Thread(new ThreadStart(this.StyleDelegate));
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        if(!StyleThread.IsAlive)
            StyleThread.Start();
    }

    protected override void OnHandleDestroyed(EventArgs e)
    {
        base.OnHandleDestroyed(e);
        lock (lockOBJ)
        {
            abortthread = true;
        }
        if (StyleThread.IsAlive)
        {
            StyleThread.Join(100);
        }
    }

    ...
}
ToolStripDropDown-Control:
public class AddPopUp : UserControl
{
    /*
        ------------------------------------
        This Control contains some CControls
        ------------------------------------
    */

    public void Show(Control control)
    {
        TSDD tsdd = new TSDD(this);
        Point screenpoint = control.PointToScreen(new Point(0, 0));
        tsdd.Show(control,new Point(0, -tsdd.Height ));
    }

    class TSDD : ToolStripDropDown
    {
        private Control Control { get; set; }

        public TSDD(Control control)
        {
            this.Control = control;
            this.DropShadowEnabled = false;
            ToolStripControlHost ch = new ToolStripControlHost(control);
            this.Items.Add(ch);
        }

        protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
        {
            base.SetBoundsCore(x, y, Control.Size.Width + 16, Control.Size.Height + 18, specified);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                unchecked
                {
                    cp.Style |= (int)0x80000000;
                    cp.Style |= 0x40000;
                }
                return cp;
            }
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x84)
            {
                m.Result = (IntPtr)1;
                return;
            }
            base.WndProc(ref m);
        }
    }
}
EDIT:
After same more testing i wasn't able to dispose the toolstripdropdown.
As a workaround i'm just destroying the handle on close of the toolstripdropdown.
        protected override void OnClosed(ToolStripDropDownClosedEventArgs e)
        {
            base.OnClosed(e);
            this.DestroyHandle();
        }

A: ToolStrips have a very persistent bug (claimed to be fixed, but I still have problems) where they register an event handler to SystemEvents.UserPreferenceChanged to be able to repaint if the user changes global style settings in the OS.
The only workaround I have found is to remove the attached toolstrips by enumerating the handlers in the SystemEvents.UserPreferenceChanged and removing them upon disposal of the control.
ToolStrip memory leak
http://connect.microsoft.com/VisualStudio/feedback/details/115600/toolstrip-leaks-after-calling-dispose#


text:
Q: manipulate object, add and group keys How can I group by month and add the values according to the position of this object?
original = {"data":[["Dic",0,0,165,0],["Ene",0,0,200,0],["Ene",150,0,0,0],["Ene",150,20,10,500]]}

what i need = {"data":[["Dic",0,0,165,0],["Ene",300,20,210,500]]}

A: Create a temporary object to group the items using the first array element values as keys. Then map new values each iteration

const original = {"data":[["Dic",0,0,165,0],["Ene",0,0,200,0],["Ene",150,0,0,0],["Ene",150,20,10,500]]}

const tmp = original.data.reduce((a,c)=>{
   a[c[0]] = (a[c[0]] ||  [c[0],0,0,0,0]).map((el,i)=> i ? el + c[i] :el);
   return a;
}, {});

original.data = Object.keys(tmp).map(key => tmp[key]);

console.log(JSON.stringify(original))


text:
Q: How to get "this" to reference parent object? I am making a Conway's Game of Life simulation in frontend. I create an object using an object constructor function. I am not done with the program. Currently, I use the object to create a table and assign each cell a css class for alive/dead. Eventually, it will also run the simulation.
I added a method to toggle the state of a cell by clicking on it. However, when I click on a cell, I would get an error in the debugger saying that such method does not exist. After playing around with it for a while, I think I reached the conclusion that "this" is not referring to the object of the object constructor function but maybe the cell that got clicked. Is this what is really happening? How can I access the parent method?
This is the offending code:
this.tableBody.addEventListener('click', function (cll) {
  const cell = cll.target.closest('td');
  if (!cell) { return }; //quit if didn't click on cell
  this.toggleState(cell.parentElement, cell.cellIndex);
});

Here is the full code:
function makeGame(rows = 5, columns = 10) {

  this.rows = rows;
  this.columns = columns;
  this.classAlive = 'alive';
  this.classDead = 'dead';
  this.table = document.createElement('table');
  this.tableBody = document.createElement('tbody');

  this.createTable = function () {

    for (let i = 0; i < this.rows; i++) {
      let row = document.createElement("tr");
      for (let j = 0; j < this.columns; j++) {
        let cell = document.createElement("td");
        cell.className = this.classDead;
        row.appendChild(cell);
      }
      this.tableBody.appendChild(row);
    }
    this.table.appendChild(this.tableBody);
    this.tableBody.addEventListener('click', function (cll) {
      const cell = cll.target.closest('td');
      if (!cell) { return }; //quit if didn't click on cell
      this.toggleState(cell.parentElement, cell.cellIndex);
    });
  }

  this.renderTable = function () {
    this.createTable();
    document.getElementById('lifes-bin').appendChild(this.table);
  }

  this.whatState = function (r, c) {
    return this.table.rows[r].cells[c].className;
  }

  this.setState = function (r, c, state) {
    this.table.rows[r].cells[c].className = state;
  }

  this.toggleState = function (r, c) {
    (this.whatState(r, c) == this.classDead) ? this.setState(r, c, this.classAlive) : this.setState(r, c, this.classDead);
  }
}

window.addEventListener('DOMContentLoaded', (event) => { startGame(); });

function startGame(r = 5, c = 10) {
  gameOfLife = new makeGame(r, c);
  gameOfLife.renderTable();
}

I've tried referencing the parent object as makeGame.toggleState but that doesn't work. I was expecting "this" to reference the object from the object constructor function. I recently created a dummy variable "papa = this;" before entering the offending code. Then I called papa.toggleState but I am assuming there is a "smarter" way.


text:
Q: how to execute multiple stored procedures and pass parameter using SSIS Initially I had one stored procedure and everything was running good but the requirement has changed now and I would like to call multiple stored procedures and pass a parameter. I am using Execute SQL Task and here is my query where it calls only one stored procedure:
EXEC [dbo].[sp_TEST]
 @Code =?
[PEDS].[up_InitialClear]

The above works well but I need to be able to call other stored procedure and pass the same parameter here. How can I call sp_TEST1, sp_TEST2 and pass the same parameter? Thanks

A: Simply execute them separately like below .
EXEC [dbo].[sp_TEST] @Code

EXEC [PEDS].[up_InitialClear] @Code


text:
Q: Request 'OPTIONS /logout' doesn't match 'POST /logout I am studying Spring Cloud and Spring OAuth2 by decomposing the three interconnected apps in this GitHub sample.  When I open up the /oauth/revoke-token endpoint in the authserver app and then call it from the ui app with a http://localhost:9999/uaa/logout, the debug log for the authserver app gives the following error message while rejecting the logout request:
Request 'OPTIONS /logout' doesn't match 'POST /logout

What specific changes need to be made to the code in the sample GitHub apps in order to enable the global logout to succeed when the ui app calls the logout function from hello.js?

INITIAL EFFORTS:

Changes that I made so far include:
Add the following @Bean definition to AuthserverApplication.java:
@Bean
public TokenStore tokenStore() {return new InMemoryTokenStore();}

Add the following controller class in the demo package of the authserver app:
@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    TokenStore tokenStore;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore);
    }

    @RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String tokenValue = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            tokenStore.removeAccessToken(accessToken);
        }
    }
}

Change the logout() method of hello.js in the ui app to become the following:
self.logout = function() {
    $http.post('http://localhost:9999/uaa/logout', {}).finally(function() {
        $rootScope.authenticated = false;
        $location.path("/");
    });
}

But when the user clicks on the logout button in the browser and triggers the call to http://localhost:9999/uaa/logout, the debug log for the authserver app gives the following output:
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/css/**']
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/css/**'
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/js/**']
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/js/**'
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/images/**']
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/images/**'
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/**/favicon.ico']
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/**/favicon.ico'
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/error']
2016-04-18 15:34:07.142 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/error'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/login']
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/login'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/authorize']
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/oauth/authorize'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/confirm_access']
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/oauth/confirm_access'

2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout']
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/logout'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : matched

2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5790c1b4
2016-04-18 15:34:07.143 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'

2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /logout' doesn't match 'POST /logout
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'

2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /logout' doesn't match 'POST /login
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /logout; Attributes: [authenticated]
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2016-04-18 15:34:07.144 DEBUG 313 --- [io-9999-exec-10] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@539015a, returned: -1
2016-04-18 15:34:07.145 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) ~[spring-security-core-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:232) ~[spring-security-core-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123) ~[spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) ~[spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:96) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) [spring-security-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    ...
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]

2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using Ant [pattern='/**', GET]
2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /logout' doesn't match 'GET /**
2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
2016-04-18 15:34:07.146 DEBUG 313 --- [io-9999-exec-10] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'http://localhost:9999/uaa/login'
2016-04-18 15:34:07.147 DEBUG 313 --- [io-9999-exec-10] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2016-04-18 15:34:07.147 DEBUG 313 --- [io-9999-exec-10] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

What other specific code changes need to be changed in the GitHub sample apps to enable the ui app to trigger a global logout of the user from all apps?
Note: Obviously, /uaa/logout is a different URL than /oauth/revoke-token.  However, the inner workings of Spring Security and OAuth in this situation are not clear without an answer to this OP.

@StuXnet's Suggestions:

The content of the Firefox Developer Tools Network Tab for the request is:
The request to http : // localhost:9999/uaa/login with method OPTIONS was rejected with a 403 error.
The raw request headers were:
Host: localhost:9999
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,x-requested-with
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

The raw response headers were:
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 20
Date: Mon, 18 Apr 2016 23:45:46 GMT
Server: Apache-Coyote/1.1
X-Application-Context: application:9999

Next, I changed the config(http) method of LoginConfig to read as follows:
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .formLogin().loginPage("/login").permitAll()
        .and()
        .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access", "/logout", "/oauth/revoke-token")
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/logout").permitAll()
        .anyRequest().authenticated();
        // @formatter:on
}

This resulted in the following new printout in the Spring Boot DEBUG logs:
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/css/**']
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/css/**'
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/js/**']
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/js/**'
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/images/**']
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/images/**'
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/**/favicon.ico']
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/**/favicon.ico'
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/error']
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/error'
2016-04-18 19:22:06.202 DEBUG 5319 --- [io-9999-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2016-04-18 19:22:06.203 DEBUG 5319 --- [io-9999-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request '/logout' matched by universal pattern '/**'
2016-04-18 19:22:06.203 DEBUG 5319 --- [io-9999-exec-10] o.s.security.web.FilterChainProxy        : /logout has an empty filter list
2016-04-18 19:22:06.204 DEBUG 5319 --- [io-9999-exec-10] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /logout
2016-04-18 19:22:06.205 DEBUG 5319 --- [io-9999-exec-10] .s.o.p.e.FrameworkEndpointHandlerMapping : Did not find handler method for [/logout]

And the following request header in Firefox:
Host: localhost:9999
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,x-requested-with
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Along with the following response header in Firefox:
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 20
Date: Tue, 19 Apr 2016 02:22:06 GMT
Server: Apache-Coyote/1.1
X-Application-Context: application:9999

I then tried changing the configure(http) method of LoginConfig to become:
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .formLogin().loginPage("/login").permitAll()
        .and()
        .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access", "/logout", "/oauth/revoke-token")
        .and()
        .authorizeRequests()
        .anyRequest().authenticated()
        // @formatter:on
        .and()
        .csrf()
        .ignoringAntMatchers("/logout");
}

But the result is the following Spring Boot DEBUG log for the authserver app:
2016-04-19 10:12:13.545 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/css/**']
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/css/**'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/js/**']
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/js/**'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/images/**']
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/images/**'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/**/favicon.ico']
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/**/favicon.ico'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/error']
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/logout'; against '/error'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request '/logout' matched by universal pattern '/**'
2016-04-19 10:12:13.546 DEBUG 4593 --- [nio-9999-exec-2] o.s.security.web.FilterChainProxy        : /logout has an empty filter list
2016-04-19 10:12:13.547 DEBUG 4593 --- [nio-9999-exec-2] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /logout
2016-04-19 10:12:13.548 DEBUG 4593 --- [nio-9999-exec-2] .s.o.p.e.FrameworkEndpointHandlerMapping : Did not find handler method for [/logout]

REPRODUCING THE PROBLEM ON YOUR MACHINE:

To reproduce the problem on your own machine, you can either:
1.) git clone the original sample app at the link at the top of the OP and then make the changes shown above, or
2.) Download the zipped version of the app as it exists on my devbox including all the changes from the OP at this file sharing link, and then:
2.a.) Untar the app.
2.b.) Navigate a terminal window to oauth2/resource and mvn spring-boot:run.  Then navigate a second terminal window to oauth2/authserver and type mvn spring-boot:run.  Then navigate a third terminal window to oauth2/ui and type mvn spring-boot:run.
2.c.) Navigate the web browser to http : // localhost:8080, then click login, then enter user for username and password for password.  After you have been authenticated, click the logout button to reproduce the 403 error.  Use the Network tab of your browser's developer tools to examine the browser activity.  View the Spring Boot logs in the terminal that is running the authserver app to see Spring's activity.
3.) Either import the three folders into eclipse (or another IDE) as existing maven projects, or open the code files with a text editor to edit before repeating the relaunch and retesting in step 2.
What else can I provide to help isolate the solution?

A: Leaving aside the question of why you might want to do this and whether or not it is a good idea: your JS client is POSTing to an endpoint on another server, so you face two problems: Cross-Origin Resource Sharing (CORS) and Cross Site Request Forgery (CSRF), both of which are locked down by default in your Auth Server because it is using Spring MVC and Spring Security.
The CORS problem can be worked around in various ways, including the approach that you took, which was to punch a hole through the security configuration using a request matcher are permitAll(). There is a far better integration between Spring MVC and Spring Security using HttpSecurity.cors(). User guide link: http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors. Simple example from the tutorial (vanilla resource server):
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        ...;
}

What this does is switch on integration with the MVC declared endpoints with @CrossOrigin. Actually the endpoint you are trying to POST to is not one that you wrote, and it's not a Spring MVC endpoint, so you might have to use cors().configurationSource(...) instead.
The CSRF problem is also easy to solve in various different ways. The tutorial where you started has explicit examples showing how to do it for Angular JS (but not in the app you are using because the tutorial is not about logging out from the SSO provider). In that case we use the HttpSecurity.csrf() features. User guide link: http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf. Simple example from the tutorial in the UI app:
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        ...
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}


text:
Q: Larger YouTube thumbnails I've been using the Youtube API to grab thumbnail images of selected videos but I need them to be a little bigger.
I need 4(ish) thumbnails at a decent size, at the moment I can generate these 3 images.
http://i.ytimg.com/vi/Cj6ho1-G6tw/1.jpg
http://i.ytimg.com/vi/Cj6ho1-G6tw/2.jpg
http://i.ytimg.com/vi/Cj6ho1-G6tw/3.jpg
But they are TINY.
I was just wondering if anyone had found a way to generate slightly larger thumbnails like the cover one.
http://i.ytimg.com/vi/Cj6ho1-G6tw/maxresdefault.jpg
This might just be something that you simply cannot do with the API but it's certainly worth a punt. I'm also open to non-API suggestions no matter how hacky.
Please note: I need all 4 thumbnails to come from the SAME video at set intervals, much like the 3 referenced above

A: You can use hq before number: http://i.ytimg.com/vi/Cj6ho1-G6tw/hq3.jpg
As I've seen - you can't use maxres thumbnails with numbers (only maxresdefault.jpg)

A: In some cases, the thumbnail will not exist with that link.
If so, you could try: https://i.ytimg.com/vi_webp/[video id]/mqdefault.webp
Or https://i.ytimg.com/vi_webp/[video id]/hqdefault.webp
mqdefault stands for Medium Quality
hqdefault is self explanatory


text:
Q: Change state of a checkbox with addEventListener in JavaScript I'm really new to JavaScript. I'm having some issues with my JavaScript code to change the state (checked or unchecked) of my checkbox input every time I click on an anchor element (the size and content is correct in CSS).
HTML simplified

  <input type="checkbox" id="nav-toggle">

JavaScript
let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
  let i = document.getElementById('nav-toggle');
  if(i.checked === false) {
     i.checked = true;
  } else {
    i.checked = false;
    }
  }
});

Let me know if my JavaScript code make sense, and what should I fix to make it work. Thanks!

A: Just tried your code and it works fine, you've just put an extra curly brace on line 9

let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
  let i = document.getElementById('nav-toggle');
  if (i.checked === false) {
    i.checked = true;
  } else {
    i.checked = false;
  }
});

  toggle
  <input type="checkbox" id="nav-toggle">

A: If all you want to do is toggle the checkbox, don't use javascript, use the HTML label element and set the for attribute to the id of the checkbox.

  <input type="checkbox" id="nav-toggle">


text:
Q: Check if memcache connection exists using PHP? According to php.net, memcache_connect() should return TRUE on success or FALSE on failure. Therefore, I thought the following code should work even if I change my cache server address to a non-existent address, but it didn't:
    $memcache=memcache_connect('myCacheServer.com', 11211);

    if($memcache){
        $this->connect=$memcache;
    }
    else{
        $memcache=memcache_connect('localhost', 11211);
        $this->connect=$memcache;
    }

Here's the error message I get:
Message: memcache_connect(): php_network_getaddresses: getaddrinfo failed: Temporary
failure in name resolution

Does anyone know how else I can set up this simple boolean?

A: As per comment, not sure why the above doesn't work, but there is a much better way of handling this.
If "myCacheServer.com" can't be connected to, then it may take up to 30 seconds each time to timeout. Then after the timeout, you'll fall back to local host - but not much point running memcached if you need to wait 30 seconds each time.
I'd recommend putting the server in a config file, or driving based off a known value - something like
if (isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') ) !== false) {
    define('MEMCAHCED_SERVER', 'localhost');
    define('MEMCAHCED_PORT', '11211');
} else {
    // assume live - alwways have live as the fallback
    define('MEMCAHCED_SERVER', 'myCacheHost.com');
    define('MEMCAHCED_PORT', '11211');
}

$memcache=memcache_connect(MEMCAHCED_SERVER, MEMCAHCED_PORT);

// Set the status to true or false.
$this->connect=$memcache;

Then, to meet your needs (if you expect the remote server to not be available) I would store this fact in a file on the server. It bit unsualy  but will save you time.
// Before calling memcache connect
if (file_exists(MyFlagFile) and filemtime(MyFlagFile) > time() - 600) {
     // Do Not Use Memcached as it failed within hte last 5 minutes
} else {
     // Try to use memcached again

     if (!$memcache) {
         // Write a file to the server with the time, stopping more tries for the next 5 minutes
         file_put_contents(MyFlagFile, 'Failed again');
     }
 }

A: I found a solution from php.net's Memcache documentation that partially works. Meaning, the errors displayed to the user are suppressed but you still have to wait for a long timeout if the cache server doesn't exist.
Here's my code for this:
    $host='myCacheServer.com';
    $port=11211;
    $memcache = new Memcache();
    $memcache->addServer($host, $port);
    $stats = @$memcache->getExtendedStats();
    $available = (bool) $stats["$host:$port"];
    if ($available && @$memcache->connect($host, $port)){
            $this->connect=$memcache;
           // echo 'true';
    }

    else{
            $host='localhost';
            $memcache->addServer($host, $port);
            $this->connect=$memcache;
            //echo 'false';
    }

A: I use this code for check connection
function checkConnection()
{
    try {
        $client = $this->initClient();
        $data = @$client->getVersion();
    } catch (Exception $e) {
        $data = false;
    }
    return !empty($data);
}


text:
Q: HTMLpurifier Add significantLink microdata itemprop to user generated html I'm using an HTML editor so that users can write forum posts. I've taken some time to develop accurate structured data. I'd like to extend that to the links that people share in their forum posts.
The following schema includes an itemprop for significantLink:
https://schema.org/WebPage

One of the more significant URLs on the page. Typically, these are the
  non-navigation links that are clicked on the most. Supersedes
  significantLinks.

This would be expressed as follows:
example

I am using HTMLpurifier to sanitize the user generated HTML. These are my current configuration settings:
require_once 'src/htmlpurifier/library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('AutoFormat.RemoveEmpty', 'true');
$config->set('AutoFormat.Linkify', 'true');
$purifier = new HTMLPurifier($config);

I wonder, how can I convert ordinary links to add this itemprop using HTMLpurifier?


text:
Q: Почему вылетает приложение после нажатия на кнопку? После нажатия на кнопку программа должна  задать значение "discrTV" (id TextView) значением из "aET" (id EditText), но она крашится. Вот код из mainactivity.java
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView discrTV = findViewById(R.id.discr);
        EditText aET = findViewById(R.id.aET);
        Button btngo = findViewById(R.id.btngo);

    btngo.setOnClickListener(this);
}

@Override
    public void onClick(View v)
    {
            String txt = aET.getText().toString();
            a = Integer.parseInt(txt);
            discrTV.setText(a);
       }

A: Метод setText() принимает строку, ты передаешь целое число:
a = Integer.parseInt(txt);
discrTV.setText(a);

Приложение ищет строку с идентификатором, равным этому числу, не находит и крашится. Нужно передавать текст:
String txt = aET.getText().toString();
discrTV.setText(txt);


text:
Q: How to change the value that a method is returning (JavaScript OOP) I'm trying to make a game in JavaScript using OOP and html5 canvas.
I can not move on with the game beacuse I'm stuck in one place.
My question is how can I change the value of method xPosition that is returning a value from a function.
Below you find some code.
var myObject = {
    //placing object in start position
    xPosition : function(){
         return Canvas.width / 2;
    },
    //if keycode pressed move myObject to the left
    move : function(){
         xPosition -= 10; //I know this wont work
    }
};

A: You can't change the return values without changing (ie. overwriting) the xPosition method itself.
However, you can easily get a value and then change that:
… move: function(){
     var xval = this.xPosition();
     xval -= 10; // this works, reassigning to the "xval" variable (xval=xval-10)

     // or in one step:
     var xval = this.xPosition() - 10;
}

Or you change the input value of the function. Let it compute the current position from canvas size and a relative position stored in a variable (or easier: in a property) and then change only that variable/property from the move function:
var myObject = {
    // placing object in start position
    xPos: 0,
    getXPosition: function() { // compute value from canvas and position
         return Canvas.width / 2 + this.xPos; // or something similar
    },
    move : function() {
         // change relative position
         this.xPos -= 10;
    }
};

A: You need to reference the correct scope of the object. The this keyword will reference the myObject scope.
You are also calling a function so need to add the brackets.
Your other issue is that you are calling a function and trying to update the value. You either need to assign xPosition as a variable or pass in the new value.
    move : function(){
         this.xPosition(-10);
    }

Have a look at these articles in structuring javascript

*

*Part 1

*Part 2

*Part 3

*Part 4
If you are dealing with x,y positions and as you say you are making a game, I would use vectors to manage your game objects. The vecotr library will handle all the maths for you. Adding, subtracting, multiplying etc.
There are a lot of vector libraries out there or you can build your own.
Vector Maths


text:
Q: Pomodoro Timer in ReactJS - Multiple instances of setIntervals running and clearInterval does not work to reset the timer I redid my Pomodoro timer but it still does not work.
This time, I have multiple instances of timers running at once.
The handlePomodoro, handleShort and handleLong functions do not work as intended.
When users trigger the above onClick effects, it is suppose to reset the timer to the desired timings. (Which it does)
However, when I run the timer, the timer keeps jumping between previous instances and the new instance.
Example:
I start with a Pomodoro ('work') time. The timer runs perfect.
But when I switch to 'break' using the handleShort function before the first timer ends. It resets the timer, and displays the correct 'break' time. The only issue is, when i start the timer again, it runs the previous and new time concurrently. So it will show like:
3:48
3:52
3:47
3:51
Please help with this clearInterval isssue.
import {Button,
    Heading,
    VStack,
    Stack,
    HStack,
    Box,
    CircularProgress,
    Text,
    CircularProgressLabel } from '@chakra-ui/react';
import { set } from 'mongoose';
import { useState, useRef, useContext, useEffect } from 'react'
import { SettingsContext } from '../helpers/SettingsContext';
import PomodoroSettings from './PomodoroSettings';

// Pomodoro
const Pomodoro = () => {

    //Timer
    const { newTimer, setNewTimer } = useContext(SettingsContext);
    const [isPaused, setIsPaused] = useState(true);
    const [minutes, setMinutes] = useState(newTimer.work);
    const [seconds, setSeconds] = useState(0);
    const [mode, setMode] = useState('work');
    const [counter, setCounter] = useState(0);
    // const [isReset, setIsReset] = useState(false);
    var isReset = false;

    const secondsLeftRef = useRef(minutes * 60 + seconds);
    const isPausedRef = useRef(isPaused);

    useEffect(() => {

        let interval = setInterval(() => {
            if (isPausedRef.current) {
                return;
            }
            if (isReset) {
                console.log("reset")
                isReset = false;
                return () => clearInterval(interval);
            }
            clearInterval(interval);
            secondsLeftRef.current--;
            if (seconds === 0) {
                if (minutes !== 0) {
                    setSeconds(59);
                    setMinutes(minutes - 1);
                } else {
                    if (mode === 'work') {
                        let minutes = newTimer.short;
                        let seconds = 0;

                        setMinutes(minutes)
                        setSeconds(seconds)
                        setMode('short')
                        secondsLeftRef.current = minutes * 60 + seconds;
                        isPausedRef.current = true;
                        setIsPaused(true);
                    } else if (mode === 'short') {
                        let minutes = newTimer.work;
                        let seconds = 0;

                        setMinutes(minutes)
                        setSeconds(seconds)
                        setMode('work')
                        secondsLeftRef.current = minutes * 60 + seconds;
                        isPausedRef.current = true;
                        setIsPaused(true);
                    } else if (mode === 'long') {
                        let minutes = newTimer.work;
                        let seconds = 0;

                        setMinutes(minutes)
                        setSeconds(seconds)
                        setMode('work')
                        secondsLeftRef.current = minutes * 60 + seconds;
                        isPausedRef.current = true;
                        setIsPaused(true);
                    }
                }
            } else {
                setSeconds(seconds - 1);
            }

        }, 1000)
    }, [seconds, mode])

    const timerMinutes = minutes < 10 ? `0${minutes}` : minutes;
    const timerSeconds = seconds < 10 ? `0${seconds}` : seconds;
    const totalSeconds = mode === 'work'
    ? newTimer.work * 60
    : newTimer.short * 60;
    const percentage = Math.round(secondsLeftRef.current / totalSeconds * 100);

    // Start / Pause
    const handleButton = (e) => {
        e.preventDefault();
        if (isPaused) {
            setIsPaused(!isPaused);
            isPausedRef.current = false;
        } else {
            setIsPaused(!isPaused);
            isPausedRef.current = true;

        }
    }

    // Pomodoro Button
    const handlePomodoro = (e) => {
        e.preventDefault();
        setMode('work');
        let minutes = newTimer.work;
        let seconds = 0;

        setMinutes(minutes)
        setSeconds(seconds)
        secondsLeftRef.current = minutes * 60 + seconds;
        isPausedRef.current = true;
        setIsPaused(true);
        isReset = true;
    }

    // Short Break Button
    const handleShort = (e) => {
        e.preventDefault();
        setMode('short');
        let minutes = newTimer.short;
        let seconds = 0;

        setMinutes(minutes)
        setSeconds(seconds)
        secondsLeftRef.current = minutes * 60 + seconds;
        isPausedRef.current = true;
        setIsPaused(true);
        isReset = true;
    }

    // Long Break Button
    const handleLong = (e) => {
        e.preventDefault();
        setMode('long');
        let minutes = newTimer.long;
        let seconds = 0;

        setMinutes(minutes)
        setSeconds(seconds)
        secondsLeftRef.current = minutes * 60 + seconds;
        isPausedRef.current = true;
        setIsPaused(true);
        isReset = true;
    }

    return (
        <div>
            <Heading as='h4' size='md'> Pomodoro </Heading>
            <VStack>
                <HStack>
                <Button variant='ghost' onClick={handlePomodoro}>
                    Pomodoro
                </Button>
                <Button variant='ghost' onClick={handleShort}>
                    Short Break
                </Button>
                <Button variant='ghost' onClick={handleLong}>
                    Long Break
                </Button>
                </HStack>
                <CircularProgress value={percentage} color={mode === 'work' ? 'red.400' : 'green.400'} size='200px' thickness='10px'>
                    <CircularProgressLabel>
                        <Text fontSize='3xl'>{timerMinutes}:{timerSeconds}</Text>
                    </CircularProgressLabel>
                </CircularProgress>
                <HStack>
                    <Button variant='outline' onClick={handleButton}>
                        { isPaused ? <div> START </div> : <div> STOP </div> }
                    </Button>
                    <PomodoroSettings />
                </HStack>
            </VStack>

        </div>
    )
}

export default Pomodoro


text:
Q: bash for loops not looping (awk, bash, linux) Here is a sample dataset (10 cols, 2 rows):
8  1   4   10  7   9   2   3   6   5
0.001475    10.001  20.25   30.5    40.75   51  61.25   71.5    81.75   92
I would like to output ten files for each dataset. Each file will contain a unique value from the second row, and the filename will contain the value from the corresponding column in the first row.
(example: a file containing .001475, called foo_bar_8.1D
See my code below, intended for use on the following datasets:
OrderTimesKC_voxel_tuning_1.txt
OrderTimesKC_voxel_tuning_2.txt
OrderTimesKC_voxel_tuning_3.txt
OrderTimesKC_voxel_tuning_4.txt
OrderTimesKC_voxel_tuning_5.txt
Script:
  subj='KC'
        for j in {1..5}; do
            for x in {1..10}; do
                a=$(awk 'FNR == 1 {print $"$x"}' OrderTimes"$subj"_voxel_tuning_"$j".txt) #a == row 1, column x
                b=$(awk 'FNR == 2 {print $"$x"}' OrderTimes"$subj"_voxel_tuning_"$j".txt) #b == row 2, column x
                echo $b > voxTim_"$subj"_"$j"_"$a".1D
            done
        done

the current outputted files are:
voxTim_KC_1_8?1?4?10?7?9?2?3?6?5.1D
voxTim_KC_2_8?1?4?10?7?9?2?3?6?5.1D
voxTim_KC_3_8?1?4?10?7?9?2?3?6?5.1D
voxTim_KC_4_8?1?4?10?7?9?2?3?6?5.1D
voxTim_KC_5_8?1?4?10?7?9?2?3?6?5.1D
these contain ten values per file, indicating that it is not looping correctly.
what I want is:

voxTim_KC_1_1.1D, voxTim_KC_1_2.1D, voxTim_KC_1_3.1D.....
voxTim_KC_2_1.1D, voxTim_KC_2_2.1D, voxTim_KC_2_3.1D.....
and so on..
Thank you!

A: awk to the rescue!
You can use awk more effectively, for example this script will do the extraction of the two values from each input file and create 10 (or actual number of columns) files with the data
 $ awk 'FNR==1{c++; n=split($0,r1); next}
        FNR==2{split($0,r2);
              for(i=1;i<=n;i++) print r2[i] > "file."c"."r1[i]".1D"}' input1 input2

will create set of files for given input1 and input2 files.  You can use this as a template and get rid of the for loops.
For example
$ tail -n 2 *
==> input1 <==
8  1   4   10  7   9   2   3   6   5
0.001475    10.001  20.25   30.5    40.75   51  61.25   71.5    81.75   92

==> input2 <==
98  91   94   910  97   99   92   93   96   95
0.001475    10.001  20.25   30.5    40.75   51  61.25   71.5    81.75   92

after running the script
$ ls
file.1.1.1D   file.1.2.1D  file.1.4.1D  file.1.6.1D  file.1.8.1D  file.2.91.1D   file.2.92.1D  file.2.94.1D  file.2.96.1D  file.2.98.1D  input1
file.1.10.1D  file.1.3.1D  file.1.5.1D  file.1.7.1D  file.1.9.1D  file.2.910.1D  file.2.93.1D  file.2.95.1D  file.2.97.1D  file.2.99.1D  input2

and contents
$ tail -n 2 file.1*
==> file.1.1.1D <==
10.001

==> file.1.10.1D <==
30.5

==> file.1.2.1D <==
61.25

==> file.1.3.1D <==
71.5

==> file.1.4.1D <==
20.25

etc...

actually, you can simply it further to
$ awk 'FNR==1{c++; n=split($0,r1)}
       FNR==2{for(i=1;i<=n;i++) print $i > ("file."c"."r1[i]".1D")}' input1 input2

A: Just with bash:
subj=KC
for j in {1..5}; do
    {
        read -ra a     # read the 1st line into array 'a'
        read -ra b     # read the 2nd line into array 'b'
        for i in {0..9}; do
            echo "${b[i]}" > "voxTim_${subj}_${j}_${a[i]}.1D"
        done
    } < "OrderTimes${subj}_voxel_tuning_${j}.txt"
done


text:
Q: lapply function with arguments I want to pick from a dataframe with a loop I'm still very new to R and haven't found any answer so far. Sorry to finally ask.
Edition with a quick example:
I want to compute a multidimensional development index based on South Africa Data.
My list is composed of individual information for each year, so basically df1 is about year 1 and df2 about year2.
df1<-data.frame(var1=c(1, 1,1), var2=c(0,0,1), var3=c(1,1,0))
df2<-data.frame(var1=c(1, 0,1), var2=c(1,0,1), var3=c(0,1,0))
mylist <-list (df1,df2)

You can find here a very simplified working index function:
myindex <- function(x, dimX, dimY){
    econ_i<- ( x[dimX]+  x[dimY] )
    return ( (1/length(econ_i))*sum(econ_i) )
    }
myindex(df1, "var2", "var3")

Then I have my dataframe of variables I want to use for my index
mydf <- data.frame(set1=c("var1", "var2"), set2=c("var2", "var3"))

I'm using a function to get arguments from database such as:
pick_values <-function(x){
    vect <-c()
    for(i in x){
    vect <- c(vect, i)
    }
    return(vect)
    }

I'd like to set up a lapply loop such that I apply my function for my list, for all sets of arguments in my dataframe. In other words, I'd like to compute my index for both years, with all sets of variables I can use. //end Edit
I've tried many unsuccessful things so far. For instance:
lapply(mylist, myindex, lapply(mydf,pick_values))

Thanks a lot for your help!

A: Okay, I don't like your mydf name nor that it has factors, so I rename it args because it has function arguments and I set stringsAsFactors = F:
args <- data.frame(set1=c("var1", "var2"), set2=c("var2", "var3"), stringsAsFactors = F)

We'll also write a wrapper for myindex that accepts a vector of arguments instead of dimX and dimY:
myindex2 = function(x, d) {
    myindex(x, d[1], d[2])
}

Then we can nest lapply like this:
lapply(mylist, function(m) lapply(args, myindex2, x = m))
# $df1
# $df1$set1
# [1] 4
#
# $df1$set2
# [1] 3
#
#
# $df2
# $df2$set1
# [1] 4
#
# $df2$set2
# [1] 3


text:
Q: Node.js change url base with prefix I have a node.js app with express and jade templates.
Just now I've running like any-host:8000 but I need to change to any-host:8000/web/
but this causes change all href and location css,img,js...
Any idea to do something to achieve transparently
I've tried with:
app.namespace('/admin', function(){...}

but then I need change the href of all the html links in the app.
Any suggestions?

A: app.use('/urlbase', express.static(__dirname + '/public'));

(assuming your app is located in myapp/).


text:
Q: Can all go libraries now be run outside of GOPATH? I read that go libraries no longer are forced to be saved under the GOPATH directory.
Do I have to modify libraries that are older or this just works for all libraries now assuming you have the correct version of Go?

A: A project using Go modules doesn't need to be under GOPATH (but you still need one for the package cache). A project using Go modules can import any library, whether or not that library uses Go modules.
A project NOT using Go modules must reside under GOPATH.


text:
Q: How to defeat Seath the Scaleless without dying at first encounter? First time you meet Seath the Scaleless he`s immortal, so you had to die to beat him later. But i knew there are some method to skip this. So any tips with it?

A: There is a (probably unintended) shortcut by jumping down from the ledge of the second elevator in the Duke's Archives onto another floor. You need an equipment load of less than 25% (fast roll) to do this.
I have found a good video explaining how to do it:
Take the elevator up. Once on the top floor, activate the lever to start the elevator down again. Quickly run onto the floor and from there roll down onto the ledge on the right (facing the floor) of the elevator that is descending. Once you see the first railing appear, jump down toward it to attempt to land on the floor. You have then skipped a whole lot of the Archives.
There is no "official" way to skip the first encounter with Seath, you're intended to die there.
As mentioned by Ben and Jubatus in the comments, you could also wear a Ring of Sacrifice during the first encounter with Seath to nullify the death penalty and keep your humanity and souls. That way you will still be treated as if you had died and can continue the level in the intended way.


text:
Q: Resolve IEnumerable with Autofac I am trying to build a mediator pipeline with Mediatr and Autofac but am struggling to resolve a collection of validators from Autofac.
public class MediatorPipeline<TRequest, TResponse>
    : IAsyncRequestHandler<TRequest, TResponse> where TRequest : IAsyncRequest<TResponse>
{
    private readonly IAsyncRequestHandler<TRequest, TResponse> _inner;
    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public MediatorPipeline(IAsyncRequestHandler<TRequest, TResponse> inner,
        IEnumerable<IValidator<TRequest>> validators)
    {
        _inner = inner;
        _validators = validators;
    }
    ...
}

When I put IValidator<TRequest> in the constructor it resolves fine, but when I put IEnumerable<IValidator<TRequest>> it fails, with the exception:

Container or service locator not configured properly or handlers not registered with your container. ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration.

Here is my registration code:
builder.RegisterAssemblyTypes(assembly)
    .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

I had the same result with this alternative registration:
var openGenericType = typeof(IValidator<>);

var query = from type in assembly.GetTypes().Where(c => !(c.GetTypeInfo().IsAbstract || c.GetTypeInfo().IsGenericTypeDefinition))
            let interfaces = type.GetInterfaces()
            let genericInterfaces = interfaces.Where(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == openGenericType)
            let matchingInterface = genericInterfaces.FirstOrDefault()
            where matchingInterface != null
            select new { matchingInterface, type };

foreach (var pair in query)
{
    builder.RegisterType(pair.type).As(pair.matchingInterface);
}

Any suggestions much appreciated!

A: First, it would be nice to see the whole exception - inner exception included - with the stack trace.
Autofac exposes a handy extension method, AsClosedTypesOf, which you can use this way:
builder
    .RegisterAssemblyTypes(ThisAssembly)
    .AsClosedTypesOf(typeof(IValidator<>))
    .InstancePerLifetimeScope();

This will do the work for you so you don't have to go into deep reflection to register your validators.
You then need to register your handlers and the decorator on top of them:
builder
    .RegisterAssemblyTypes(ThisAssembly)
    .AsClosedTypesOf(typeof(IAsyncRequestHandler<,>), "base-handler")
    .InstancePerDependency();

builder.RegisterGenericDecorator(
    typeof(MediatorPipeline<,>),
    typeof(IAsyncRequestHandler<,>),
    "base-handler");


text:
Q: ls | egrep | xargs rm I have a group of files I'd like to remove at once.
ls | egrep \^New

The output is as expected,
New 1
New 2
New 3

but continuing the pipe with
| xargs -L rm

attempts to remove the input as space-delimited:
rm: New: No such file or directory
rm: 1: No such file or directory

What am I missing?

A: Don't parse ls. This should do the trick:
rm New*

Your approach is failing because xargs splits arguments up on whitespace by default, so it runs rm on New, 1, New, 2 etc. You could work around that by splitting on newlines, but that won't work with filenames containing newlines.

A: Yes you're right, xargs is breaking up the file names at the spaces. If you're using GNU xargs you can have it use a newline as the delimiter with the -d option. Example:
ls | egrep \^New | xargs -d '\n' rm


text:
Q: How to achieve this for loop in R? I'm trying to write a for-loop of a dataset. Just to make it simple, I'll write an example:
 Two variables, X and Y.
         X = 3, 6, 9
         Y = 4, 8, 12

I want to make a loop that does this:
   (Xi - Yi)^2, so first (3-4)^2, then
   (6-8)^2 and so on.

Then, after that is done, multiply by this:
   ((1/2)/(n*(n-1))).

In this example, it would be:
     (3-4)^2 + (6-8)^2 + (9-12)^2 = 1 + 4 + 9 = 14
     1/2 / (3*(3-1)) = 0.5 / 6 = 0.0833.
     0.0833 * 14 = 1.166.

    result <- 0
    sum <- rep(NA, n)
        for (i in (1:n)) {
          for(j in (1:n)) {
          sum <- ((gathered$X[i] - gathered$X[j])^2)
     }
      }

A: Usually in R you can avoid for loops most of the times. For your case you can do
sum((X - Y)^2) * (1/2)/(length(X) * (length(X) - 1))
#[1] 1.166666667

However, as far as for loop is concerned you should be using a single loop since you want to access X[i] and Y[i] together.
sum <- 0
n <- 3
for (i in (1:n)) {
    sum <- sum + (X[i] - Y[i])^2
 }
sum * (1/2)/(n*(n-1))
#[1] 1.1667

data
X = c(3, 6, 9)
Y = c(4, 8, 12)

A: How about this, i think outer is fit to your problem.
CASE 1 ( X-Y )
sum(diag(outer(X,Y,function(X,Y)(X-Y)^2))) *
 (1/2)/(length(X) * (length(X) - 1))
1.166667

CASE 2 ( all X and Y calculation )
sum(outer(X,Y,function(X,Y)(X-Y)^2)) *
(1/2)/(length(X) * (length(X) - 1))
15.5


text:
Q: openvpn: this is a generic configuration and cannot directly be used I have experienced a problem.
I have installed OpenVPN AS on VPS.
Used .ovpn config with OpenVPN Connect on my Windows 7 desktop. Works fine.
When I tried to configure VPN connection on Ubuntu, I have experienced following errors:

*

*via command line:
sudo openvpn ~/Downloads/server-locked.ovpn
this is a generic configuration and cannot directly be used

*via network connections manager (which has icon placed on status bar, near time) -> VPN Connections - > Configure VPN -> Import
I receive Cannot import VPN Connection:
The file '.ovpn' could not be read or does not contain recognized VPN connection information
Error: The file to import wasn't a valid OpenVPN client configuration..

what I already tried:
sudo apt-get install openvpn
sudo apt-get install network-manager-vpnc
sudo apt-get install network-manager-vpnc-gnome

What I should to do to make it work with *.ovpn file?
Content of my server-locked.ovpn file
# Automatically generated OpenVPN client config file
# Generated on Sat Mar 29 11:51:42 2014 by main
# Define the profile name of this particular configuration file
# OVPN_ACCESS_SERVER_PROFILE=.../Dynamic
# OVPN_ACCESS_SERVER_DYNAMIC=1
# OVPN_ACCESS_SERVER_CLI_PREF_ALLOW_WEB_IMPORT=True
# OVPN_ACCESS_SERVER_CLI_PREF_ENABLE_CONNECT=True
# OVPN_ACCESS_SERVER_CLI_PREF_ENABLE_XD_PROXY=True
# OVPN_ACCESS_SERVER_WSHOST=...:443
# OVPN_ACCESS_SERVER_WEB_CA_BUNDLE_START
# -----BEGIN CERTIFICATE-----
# -----END CERTIFICATE-----
# OVPN_ACCESS_SERVER_WEB_CA_BUNDLE_STOP
# OVPN_ACCESS_SERVER_IS_OPENVPN_WEB_CA=1
# OVPN_ACCESS_SERVER_ORGANIZATION=OpenVPN Technologies, Inc.
setenv FORWARD_COMPATIBLE 1
# OVPN_ACCESS_SERVER_GENERIC=1

setenv GENERIC_CONFIG
<ca>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</ca>
## -----BEGIN RSA SIGNATURE-----
## DIGEST:sha256
## -----END RSA SIGNATURE-----
## -----BEGIN CERTIFICATE-----
## -----END CERTIFICATE-----
## -----BEGIN CERTIFICATE-----
## -----END CERTIFICATE-----

A: Just download client.ovpn instead of server-locked.ovpn and all works fine for now via command line. Looks like magic, but works.

A: I think you have to edit / re-download your OpenVPN configuration.
The reason is that the server-locked.ovpn you posted does not contain the address of your VPS. It should probably be on the line
# OVPN_ACCESS_SERVER_WSHOST=...:443

So it looks like your current configuration file does not actually contain any settings and the message
this is a generic configuration and cannot directly be used

is an error message telling you that the problem is with your configuration.


text:
Q: How to drag a component with animation in React I am trying to drag a component whose css has transform animation.
But it could not work.
The component just move according to animation and could not be dragged.
Is there any way to achieve the drag function?

import * as React from "react";
import {
  theComponent
} from "../style.css";
import Draggable from "react-draggable";

class DragMe extends React.Component {
  render() {
    return (
      <Draggable
        axis="both"
        handle=".handle"
        defaultPosition={{ x: 0, y: 0 }}
        position={null}
        grid={[25, 25]}
        scale={1}
        onStart={this.handleStart}
        onDrag={this.handleDrag}
        onStop={this.handleStop}
      >

Drag Me!

      </Draggable>
    );
  }
}
. theComponent{
  animation: moveAnimation 3.5s infinite;
}

@keyframes moveAnimation {
  0%,
  100% {
    transform: translate(-200%, 20%);
  }
  50% {
    transform: translate(-200%, 25%);
  }
}

A: If you change css animation from  transform to top, left, inline styles transform will be work and dragged. Try rewrite css like this example
.theComponent {
  position: relative;
  animation: moveAnimation 3.5s infinite;
}
@keyframes moveAnimation {
  0%,
  100% {
    top: 5px;
  }
  50% {
     top: 0px;
  }
}


text:
Q: Adding external ram to 2014 MacBook Pro I'm new to macs so please bear with me if I say something dumb.
I recently switched over to Mac, and purchased a new MacBook Pro, but found that the computer did not have enough ram for everything I am doing (large photoshop files etc.) I was wondering if there is any way that I could get external ram or some type of upgrade for my computer.
Essentially, can I get an external ram drive, or should I go back and upgrade the computer itself?

A: The internal RAM is soldered to the motherboard (i.e. totally user-untouchable), but for external RAM, you're welcome to check out this article at your own risk.
UPDATE: After having done some research, apparently RAM disks are exactly the opposite of what I'd thought. They actually turn a segment of your RAM into hard drive space. It still promises massive speed boosts, though, so you should give it a try if you're up for it!

A: I'm sorry, but no, you can't upgrade.


text:
Q: Como criar um serviço do Windows na instalação Vou distribuir minha aplicação feita em Delphi através de um instalador padrão criado com o Install Shield, mas ela necessita criar um serviço do Windows para funcionar. Sei com criar esse serviço manualmente, mas não como criá-lo pelo o Install Shield.
Por favor alguém pode me explicar como criar um serviço do Windows usando o Install Shield?
Obrigado.


text:
Q: Log when file is requested from server I need a way to log an entry into a database, everytime a particular file is requested from the server. The file can be any type, even images or other media.
Is it also possible to log which IP address or hostname has requested that file?

A: What's the language? HTTP handler technology?
Example: java/servlet, ruby/rails, php/apache...
In either case you can analyze the log file easily: HTTP log files contain ip, file name, timestamp.
It would be a ten lines in perl+DBI to parse apache's config and count downloads into database. Stuck it int cron and be done.


text:
Q: How can I attach an avatar to a JIRA user manually (through API or database operations)? We are using JIRA 4.4 with crowd.
We want to dump users photos from Active Directory into the avatar folder (inside jira-home directory) and than to automatically associate those photos with JIRA users (we don't want each and every user having to manualy choose their avatar).
Can this be done through database insert/update operations?

A: This answer may not be too helpful but have you already looked into this? The only problem is that the REST API for managing avatars was introduced in JIRA 5.0+
I'm not aware of a easy way of doing it on JIRA 4.4 unfortunately.


text:
Q: sinopia -- how to configuring proxy settings for npmps I recently downloaded sinopia server in order to cache packages locally, to save internet bandwidth.  But it is not working as expected, as I am working behind a corporate proxy.  In my setup, I have installed sinopia on my own local mac pc, and I am able to access the url (http://localhost:L4873/) in a browser.
Since, I work behind a proxy, i have properly configured
 - npm config set http-proxy
 - npm config set https-proxy
I verified the settings and it works without sinopia intervening.
But, when sinopa server is running, if I run npm install , there is no request landing on sinopia, as I finally get error 502.
If I remove the npm proxy settings, and then run npm install , then this time there is a hit to sinopia server, but now the sinopia server fails with connection refused error to a public url.
Is there a way to specify proxy settings for sinopia, without specifying npm config proxy ... ?

A: Verdaccio is a sinopia's fork and we have documented how to do it.
http://www.verdaccio.org/docs/en/configuration.html#proxy
Configuration is almost the same, so, it might be useful for you.


text: Q: ¿Cómo agregar texto en los espacios en blanco con ironpdf? mi pregunta es si ironpdf tiene la funcionalidad de agregar texto en los espacios en blanco de un archivo html antes de convertirlo a pdf. Gracias por adelantado.


text:
Q: Is there any way to set Python IDLE's interactive shell indentation width to 2 spaces instead of its default? I'm not asking about Options > Configure IDLE > Fonts/Tabs > Indentation Width and setting that to 2. This only sets the indentation width within a file and not the indentation width for the interactive shell.
What Python IDLE file do I need to change to get 2-space spacing in the interactive shell?
I like to code with 2 spaces instead of 4 so not having the interactive shell also indent by the same spacing slows me down when transferring out of shell and into a file for example.

A: No, not at present.
Shell currently uses tabs to indent, and tabs are fixed in tk as 8 'spaces'.  I believe at least part of the reason is so that follow-up lines are visually indented in spite of the >>> prompt.
I don't like this either.  In the future, I would like to move the prompt into a sidebar so that entered code starts flush left, as in the editor, and can use the same user-set indent as in the editor.

A: There is a solution!!! *1
Solution
go to idlelib (/lib/idlelib/) *2
open "pyshell.py"
go to class PyShell, __init__
there are 3 lines
self.usetabs = True
# indentwidth must be 8 when using tabs.  See note in EditorWindow:
self.indentwidth = 8

just change them to
self.usetabs = False
# indentwidth must be 8 when using tabs.  See note in EditorWindow:
self.indentwidth = 4 # you decide, lot of people prefer 2

P.S.
this will result in wierd looks:
>>> def f(x): # calculate x*abs(x)
    if x > 0: # it doesn't look it, but this is indented once
        return x*x # and this twice
    else:
        return -x*x

But I think it looks better then 8-spaces-tab indent
footnotes
*1 I'm working with python 3.8 on windows 10, but this may work elsewhere
*2 depending where python is installed
step 1: find python (to me it is "C:\Programs\Python 3.8")
step 2: from there go to /lib/idlelib/


text:
Q: Remove filesystem from an unpartitioned disk I have an un-partitioned 500GB disk with a ext3 fs using the entire disk.
If I make sure there are no partitions on the disk using fdisk or parted, "ssm list" will still show an ext3 fs on the disk (because this file system exists outside of any partitions"
I am also still able to mount the fs and use it.
How can I remove any reference to this filesystem?
I'm using centos7  and there is no data on the disk that I want to keep.
The server is running in a VM, I could just add a new disk to it, but I want to know how to do it.

A: An alternative to scrubbing all the data is to use the wipefs utility from the util-linux package.  Run it without arguments to list the signatures found on the device:
# wipefs /dev/sdb
offset               type
----------------------------------------------------------------
0x0                  xfs   [filesystem]
                     UUID:  72f2a607-8af7-44c0-83c2-f1565cd68a1a

Then run it with -a to erase those signatures:
# wipefs -a /dev/sdb
/dev/sdb: 4 bytes were erased at offset 0x00000000 (xfs): 58 46 53 42

# wipefs /dev/sdb
#

This will not delete your data.  It'll just remove the filesystem headers so that it's not mountable.

A: One easy (and heavy handed) way to do this would be to wipe the whole contents of the disk.  The simplest way to do that would be to use dd:
$ sudo dd if=/dev/zero of=/dev/<disk> bs=1M count=500000

By the time the command ends (maybe an hour?) your whole disk will be filled with zeros.
If you're in a rush, you could kill the process with Ctl+C after a few seconds/minutes to see if you've wiped enough data for the disk to be considered as blank.