text:
Q: Spark on kubernetes: driver dies -> executors hit self destruct sequence but do not die I have an issue wherein driver containers are being killed in such a way that the child processes (ie the spark driver) are not being cleaned up appropriately. This leaves leaked executors.  However, my understanding is that if executors should lose contact with the driver they should self destruct. Indeed they claim to do so, but then... do not.

21/02/25 17:43:59 INFO TransportClientFactory: Successfully created connection to /10.178.144.144:37811 after 2 ms (0 ms spent in bootstraps)
21/02/25 17:43:59 INFO ShuffleBlockFetcherIterator: Started 8 remote fetches in 48 ms
21/02/25 17:43:59 INFO CodeGenerator: Code generated in 21.223892 ms
21/02/25 17:43:59 INFO Executor: Finished task 0.0 in stage 2.0 (TID 97). 2661 bytes result sent to driver
21/02/26 19:56:58 ERROR CoarseGrainedExecutorBackend: Executor self-exiting due to : Driver 10.205.36.205:32000 disassociated! Shutting down.
21/02/26 19:56:58 INFO MemoryStore: MemoryStore cleared
21/02/26 19:56:58 INFO BlockManager: BlockManager stopped

However, the executor docker container is still running and the executor process is still running inside. No further output.
Edit: I've tracked this down to a deadlock in a shutdown hook
"Thread-2" #26 prio=5 os_prio=0 tid=0x00007f6410231800 nid=0x2a2 waiting on condition [0x00007f63c3bf1000]
java.lang.Thread.State: TIMED_WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000000c05a47b8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
at java.util.concurrent.ThreadPoolExecutor.awaitTermination(ThreadPoolExecutor.java:1475)
at java.util.concurrent.Executors$DelegatedExecutorService.awaitTermination(Executors.java:675)
at org.apache.spark.rpc.netty.MessageLoop.stop(MessageLoop.scala:60)org.apache.spark.rpc.netty.Dispatcher.$anonfun$stop$1(Dispatcher.scala:190)
at org.apache.spark.rpc.netty.Dispatcher.$anonfun$stop$1$adapted(Dispatcher.scala:187)
at org.apache.spark.rpc.netty.Dispatcher$$Lambda$214/337533935.apply(Unknown Source)
at scala.collection.Iterator.foreach(Iterator.scala:941)
at scala.collection.Iterator.foreach$(Iterator.scala:941)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
at scala.collection.IterableLike.foreach(IterableLike.scala:74)
at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
at org.apache.spark.rpc.netty.Dispatcher.stop(Dispatcher.scala:187)
at org.apache.spark.rpc.netty.NettyRpcEnv.cleanup(NettyRpcEnv.scala:324)
at org.apache.spark.rpc.netty.NettyRpcEnv.shutdown(NettyRpcEnv.scala:302)
at org.apache.spark.SparkEnv.stop(SparkEnv.scala:96)
at org.apache.spark.executor.Executor.stop(Executor.scala:292)
at org.apache.spark.executor.Executor.$anonfun$new$2(Executor.scala:74)
at org.apache.spark.executor.Executor$$Lambda$317/1046854795.apply$mcV$sp(Unknown Source)
at org.apache.spark.util.SparkShutdownHook.run(ShutdownHookManager.scala:214)
at org.apache.spark.util.SparkShutdownHookManager.$anonfun$runAll$2(ShutdownHookManager.scala:188)
at org.apache.spark.util.SparkShutdownHookManager$$Lambda$2192/1832515374.apply$mcV$sp(Unknown Source)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1932)
at org.apache.spark.util.SparkShutdownHookManager.$anonfun$runAll$1(ShutdownHookManager.scala:188)
at org.apache.spark.util.SparkShutdownHookManager$$Lambda$2191/952019066.apply$mcV$sp(Unknown Source)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at scala.util.Try$.apply(Try.scala:213)
at org.apache.spark.util.SparkShutdownHookManager.runAll(ShutdownHookManager.scala:188)
at org.apache.spark.util.SparkShutdownHookManager$$anon$2.run(ShutdownHookManager.scala:178)
at org.apache.hadoop.util.ShutdownHookManager$1.run(ShutdownHookManager.java:54)


text:
Q: Task cancellation in SwiftUI I have come across a strange behavior (or at least one I don't understand) while trying to cancel a Task. Here is a minimal example: I have a Task that sleeps 30 seconds and then increment a counter.
However, if I call .cancel() on that Task before 30 seconds have passed then the counter is incremented immediately.
I would have expected that cancelling the Task would not increment the counter value; does anyone have an idea of what is going on here?
Thank you!
import SwiftUI

struct ContentView: View {
    @State var task: Task<Void, Never>? = nil  // reference to the task
    @State var counter = 0

    var body: some View {
        VStack(spacing: 50) {

            // display counter value and spawn the Task
            Text("counter is \(self.counter)")
                .onAppear {
                    self.task = Task {
                        try? await Task.sleep(nanoseconds: 30_000_000_000)
                        self.counter += 1
                    }
                }

            // cancel button
            Button("cancel") {
                self.task?.cancel()  // <-- when tapped before 30s, counter value increases. Why?
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: When a task is canceled an error is thrown but you are ignoring the thrown error by using try?
Here is a variant of your code that will react properly to the cancellation
self.task = Task {
    do {
        try await Task.sleep(nanoseconds: 30_000_000_000)
        self.counter += 1
    } catch is CancellationError {
        print("Task was cancelled")
    } catch {
        print("ooops! \(error)")
    }

A: How about adding a check for isCancelled like this:
Text("counter is \(self.counter)")
    .onAppear {
        print("onappear..")
        self.task = Task {
            try? await Task.sleep(nanoseconds: 30_000_000_000)
            if !self.task!.isCancelled {
                self.counter += 1
            }
        }
    }

A: Placing the code inside a do catch block is enough.
self.task = Task {
    do {
        try await Task.sleep(nanoseconds: 3_000_000_000)
        self.counter += 1
    } catch {
        print(error)
    }
}

A: In SwiftUI it's best to use the .task modifier to use async/await, e.g.
@State var isStarted = false
...
Button(isStarted ? "Stop" : "Start") {
    isStarted.toggle()
}
.task(id: isStarted) {
    if !isStarted {
        return
    }
    do {
        try await Task.sleep(for: .seconds(3))
        counter += 1
    } catch {
        print("Cancelled")
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change column order in a table using sql query in sql server 2005? How to change column order in a table using SQL query in SQL Server 2005?
I want to rearrange column order in a table using SQL query.

A: You can do it by creating a new table, copy all the data over, drop the old table, then renaming the new one to replace the old one.
You could also add new columns to the table, copy the column by column data over, drop the old columns, then rename new columns to match the old ones. A simple example below:
http://sqlfiddle.com/#!3/67af4/1
CREATE TABLE TestTable (
    Column1 INT,
    Column2 VARCHAR(255)
);
GO

insert into TestTable values(1, 'Test1');
insert into TestTable values(2, 'Test2');
GO

select * from TestTable;
GO

ALTER TABLE TestTable ADD Column2_NEW VARCHAR(255);
ALTER TABLE TestTable ADD Column1_NEW INT;
GO

update TestTable
set Column1_NEW = Column1,
    Column2_NEW = Column2;
GO

ALTER TABLE TestTable DROP COLUMN Column1;
ALTER TABLE TestTable DROP COLUMN Column2;
GO

sp_rename 'TestTable.Column1_NEW', 'Column1', 'COLUMN';
GO
sp_rename 'TestTable.Column2_NEW', 'Column2', 'COLUMN';
GO

select * from TestTable;
GO

A: In SQLServer Management Studio:
Tools -> Options -> Designers -> Table and Database Designers
Unselect Prevent saving changes that require table re-creation.
Now you can reorder the table.

A: You have to explicitly list the fields in the order you want them to be returned instead of using * for the 'default' order.
original query:
select * from foobar

returns
foo bar
--- ---
  1   2

now write
select bar, foo from foobar

bar foo
--- ---
  2   1

A: Sql server internally build the script. It create a temporary table with new changes and copy the data and drop current table then recreate the table insert from temp table. I find it from "Generate Change script" option ssms 2014. Script like this. From Here: How to change column order in a table using sql query
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_emps
    (
    id int NULL,
    ename varchar(20) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_emps SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.emps)
     EXEC('INSERT INTO dbo.Tmp_emps (id, ename)
        SELECT id, ename FROM dbo.emps WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.emps
GO
EXECUTE sp_rename N'dbo.Tmp_emps', N'emps', 'OBJECT'
GO
COMMIT

A: according to https://learn.microsoft.com/en-us/sql/relational-databases/tables/change-column-order-in-a-table

This task is not supported using Transact-SQL statements.

Well, it can be done, using create/ copy / drop/ rename, as answered by komma8.komma1
Or you can use SQL Server Management Studio

*

*In Object Explorer, right-click the table with columns you want to reorder and click Design (Modify in ver. 2005 SP1 or earlier)

*Select the box to the left of the column name that you want to reorder. (You can select multiple columns by holding the [shift] or
the [ctrl] keys on your keyboard.)

*Drag the column(s) to another location within the table.

Then click save. This method actually drops and recreates the table, so some errors might occur.
If Change Tracking option is enabled for the database and the table, you shouldn't use this method.
If it is disabled, the Prevent saving changes that require the table re-creation option should be cleared in Tools menu > Options > Designers, otherwise "Saving changes is not permitted" error will occur.

*

*Disabling the Prevent saving changes that require the table re-creation option is strongly advised against by Microsoft, as it leads to the existing change tracking information being deleted when the table is re-created, so you should never disable this option if Change Tracking is enabled!
Problems may also arise during primary and foreign key creation.
If any of the above errors occurs, saving fails which leaves you with the original column order.

A: If your table has enough columns then you can try this. First create a new table with preferred order of columns.
    create table new as select column1,column2,column3,....columnN from table_name;

Now drop the table using drop command
    drop table table_name;

now rename the newly created table to your old table name.
    rename new to table_name;

now select the table, you have your columns rearranged as you preferred before.
    select * from table_name;

A: Not sure if still relevant, but SSMS can generate a change scripts for this.

*

*Re-order (drag the column) the table in Designer View

*Click on 'Generate Change Script'

The generated script contains the script which does the following:

*

*Create a temporary table

*Adds the constraints, relationships and triggers from original table to temporary table

*Drop original table

*Rename temporary table to original table name

A: In SQLServer Management Studio:
Tools -> Options -> Designers -> Table and Database Designers

*

*Unselect 'Prevent saving changes that require table re-creation'.

Then:

*

*right click the table you want to re-order the columns for.

*click 'Design'.

*Drag the columns to the order you want.

*finally, click save.

SQLServer Management studio will drop the table and recreate it using the data.

A: You cannot. The column order is just a "cosmetic" thing we humans care about - to SQL Server, it's almost always absolutely irrelevant.
What SQL Server Management Studio does in the background when you change column order there is recreating the table from scratch with a new CREATE TABLE command, copying over the data from the old table, and then dropping it.
There is no SQL command to define the column ordering.

A: This is similar to the question on ordering the records in the result of a query .. and typically no one likes the formally correct answer ;-)
So here it goes:

*

*as per SQL standard, the columns in a table are not "ordered"

*as a result, a select * does not force the columns to be returned in a particular order

*typically, each RDBMS has a kind of "default" order (usually the order that the columns were added to the table, either in the create table' or in thealter table add ` statements

*therefore, if you rely on the order of columns (because you are using the results of a query to poulate some other datastructure from the position of the columns), explicitly list the columns in the order you want them.

A: You can of course change the order of the columns in a sql statement. However if you want to abstract tables' physical column order, you can create a view. i.e
CREATE TABLE myTable(
    a int NULL,
    b varchar(50) NULL,
    c datetime NULL
);

CREATE VIEW vw_myTable
AS
SELECT c, a, b
  FROM myTable;

select * from myTable;
a  b  c
-  -  -

select * from vw_myTable
c  a  b
-  -  -

A: If you have not yet added any data into your table yet, there is one way to move the columns around.
Try this:

*

*In SSMS, click Tools > Options > Designers > Table and Database Designers > Uncheck the box next to Prevent saving changes that require table re-creation > Click OK.

*In the object tree, right-click on your table and select Design > in the thin column to the left of the Column Name column, you can click and drag the columns around to wherever you want them. When you're done, just go to close the Design tab and SSMS will ask you if you want to save your changes, click OK.

Optional:
3. Re-enable the checkbox for the option from Step 1 to re-secure your table.
Hope this helps someone!
Credit goes to Microsoft:
https://learn.microsoft.com/en-us/troubleshoot/sql/ssms/error-when-you-save-table#more-information

A: At the end of the day, you simply cannot do this in MS SQL. I recently created tables on the go (application startup) using a stored Procedure that reads from a lookup table. When I created a view that combined these with another table I had manually created earlier one (same schema, with data), It failed - simply because I was using ''Select * UNION Select * ' for the view. At the same time, if I use only those created through the stored procedure, I am successful.
In conclusion: If there is any application which depends on the order of column it is really not good programming and will for sure create problems in the future. Columns should 'feel' free to be anywhere and be used for any data process (INSERT, UPDATE, SELECT).

A: You can achieve it with these steps:

*

*remove all foreign keys and primary key of the original table.

*rename the original table.

*using CTAS create the original table in the order you want.

*drop the old table.

*apply all constraints back to the original table

A: If the columns to be reordered have recently been created and are empty, then the columns can be deleted and re-added in the correct order.
This happened to me, extending a database manually to add new functionality, and I had missed a column out, and when I added it, the sequence was incorrect.
After finding no adequate solution here I simply corrected the table using the following kind of commands.
ALTER TABLE  tablename  DROP COLUMN  columnname;
ALTER TABLE  tablename  ADD columnname columntype;

Note: only do this if you don't have data in the columns you are dropping.
People have said that column order does not matter. I regularly use SQL Server Management Studio "generate scripts" to create a text version of a database's schema. To effectively version control these scripts (git) and to compare them (WinMerge), it is imperative that the output from compatible databases is the same, and the differences highlighted are genuine database differences.
Column order does matter; but just to some people, not to everyone!

A: Example: Change position of field_priority after field_price in table status.
ALTER TABLE `status` CHANGE `priority` `priority` INT(11) NULL DEFAULT NULL AFTER `price`;

A: You can change this using SQL query. Here is sql query to change the sequence of column.
ALTER TABLE table name
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;

A: alter table name modify columnname int(5) first;
will bring the column to first
alter table name modify columnname int(5) after (tablename);

A: This worked for me on Oracle DB:
select column1, column2, t.* from table t

A: Use
SELECT * FROM TABLE1

which displays the default column order of the table.
If you want to change the order of the columns.
Specify the column name to display correspondingly
SELECT COLUMN1, COLUMN5, COLUMN4, COLUMN3, COULMN2 FROM TABLE1

A: you can use indexing.. After indexing, if select * from XXXX results should be as per the index, But only result set.. not structrue of Table

A: In order to have a specific column order You need to select column by column in the order You wish.
Selection order dictates how columns will be ordered in output.

A: Try this command:
alter table students modify age int(5) first;

This will change the position of age to the first position.


text:
Q: Remove blank rows in table I'm trying to run a macro that selects blank cells in a table column and deletes the entire row.
The script below does everything except the deleting part, which prompts the following error:

run-time error 1004 - "Delete method of Range class failed"

I have used the following code:
Sub test()
Range("Table1[[New]]").Activate
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
End Sub

A: You actually can do it in one pass, but need to use the ListObject object and its DataBodyRange and ListColumns properties:
Sub ClearBlankCellsInColumnNew()
Dim rngBlanks As Excel.Range

With Worksheets("Sheet1").ListObjects("Table1")
    On Error Resume Next
    Set rngBlanks = Intersect(.DataBodyRange, .ListColumns("New").Range).SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0
    If Not rngBlanks Is Nothing Then
        rngBlanks.Delete
    End If
End With
End Sub

A: Nice question! Without a table, .EntireRow.Delete always works, but inside a table it looks like as it doesn't.
This works:
Sub Test()
  Dim Rng As Range
  On Error Resume Next
  Set Rng = Range("Table1[[New]]").SpecialCells(xlCellTypeBlanks)
  On Error Goto 0
  If Not Rng Is Nothing Then
    Rng.Delete Shift:=xlUp
  End If
End Sub

A: Step 1: Make a helper column in the table where you check for any blank fields in that row. For example, if you had 3 columns in your table: A (Price), B (Quantity), and C (Cost), you would add a fourth column D and label it "Any Blanks?".  The equation would be =IF(OR(ISBLANK([@Price]),ISBLANK([@Quantity]),ISBLANK([@Cost])),"Yes","No")
That would give you a column to filter to view all the blanks.
Step 2: In VBA you would then do the following:
Range("MyTableNameHere").AutoFilter Field:=Range("MyTableNameHere[Any Blanks?]").Column, Criteria1:="Yes"
Application.DisplayAlerts = False
Range("MyTableNameHere").ListObject.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
Range("MyTableNameHere").AutoFilter Field:=Range("MyTableNameHere[Any Blanks?]").Column

This essentially is filtering to the rows you want to delete in the table using the helper column, selecting all the visible data in the table, and unfiltering the table.  I was searching around how to delete all visible rows in a table and found this and fiddled around until I figured out that this would work.  Taking that and combining it with a helper column to select all rows with any blanks seems like what you were wanting as well.

A: Adapting previous answers:
On Error Resume Next
Set Rng = ListObjects(1).DataBodyRange.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not Rng Is Nothing Then
Rng.Delete Shift:=xlUp
End If

A: This One liner also would help
on error resume next 'to continue macro if no empty row is found in table
.Range("Table1").Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
'this delete empty using 1st column as reference for checking blanks
'Use custom names for tables for easy manipulation in codes

A: Using ListObjects in Excel makes it easy to use the following to remove blank rows.
Sub RemoveBlankRow(ByVal SheetName As String, TableName As String)
Dim rng As Integer

rng = Sheets(SheetName).ListObjects(TableName).DataBodyRange.Rows.Count

For i = 1 To rng
    If Application.WorksheetFunction.CountA(Rows(i)) = 0 Then Rows(i).EntireRow.Delete
Next
End Sub

A: Two notes regarding Frej Lindstrom's solution, which I used but had to tweak a little:

(1) add an End If before the Next
(2) add "i = i - 1" just before the End If

Why? because if you have blank rows one above each other, you'll skip one since all the rows' numbers just shifted one up. Essentially, if you deleted row [N], another row is now row [N], and you need to also test it rather than moving immediately to row [N + 1].
BIG CAVEAT: if your last row is blank, this will give you a stuck loop. I'll probably put in an IF to handle it, though.
I know this is an old thread, but thought I'd add this in case anyone else comes through looking for similar solutions. Thank you to Frej - your code really helped!

A: This is my solution:
Public Sub remove_blank_rows(sh As Worksheet)

    Dim tbl As ListObject
    Set tbl = sh.ListObjects(1)
    Dim i As Long
    Dim ii As Long

    Application.EnableEvents = False

    ii = tbl.Range.rows.Count
    For i = 2 To ii
        If WorksheetFunction.CountA(rows(i)) = 0 Then

            rows(i).EntireRow.Delete

            ii = tbl.Range.rows.Count
            If i >= ii Then
                GoTo A
            End If

            If i > 1 Then
                i = i - 1
            End If

        End If
    Next
A:

    Application.EnableEvents = True
End Sub

Note that when you delete a row, all the rows below it will shift up by 1 and this is why index i is decremented in order to again check the same row in the next iteration! Note however that i need not exceed certain limits and this is done with the two  If sentances.


text:
Q: Pass row id when clicking button in report So I have a report that I have included a button to the detail area of the report, so every row has a button.  The button's On Click is set to btnCheck_Click().  How do I get the Id field of that row to my VBA function?  From there it does some sanity checking and then re-queries the form to refresh it.  But I need to pass it that ID.  So on a page of 100 records I have 100 id's, how do I reference the right one?

A: Assuming your ID field is either bound to a control on the form, or at least defined in the recordset if not bound, or if you mean the current RECORD NUMBER, the following will work:
Private Sub btnCheck_Click()
    MsgBox Me.ID & vbTab & Me!ID & vbtab & CurrentRecord   ' Bound Field Content  |  Unbound Field  |  Current Record
End Sub


text:
Q: WordPress Contributor Moderation Comments If user has permission "Contributor" in Admin Page can View the comments awaiting moderation but i need to disable this.
In user roles with "View comments Awaiting Moderation" its not present nothing.
How to disable the /wp-admin/edit-comments.php?comment_status=moderated for Contributor users?

A: You could bypass it with javascript adding a script only for logged in users with contributor role removing comment rows with unapproved class from dom.
check if user is logged and is contributor:
if( is_user_logged_in() && current_user_can('contributor')) {

then add a script inline or enqueue a js file with the follwing code:
$('#the-comment-list tr.unapproved').remove();

check if the comments are visible in any other views and add the corresponding classes to the script to remove them form everywhere
/* edit */
vanilla js script:
var elem = document.getElementById("the-comment-list");

for (var i = 0; i < elem.childNodes.length; i++) {
   if (/\bunapproved/.test(elem.childNodes[i].className)) {
      elem.childNodes[i].parentNode.removeChild(elem.childNodes[i]);
   }
}

A: Modify the comments query
Here's one suggestion, to adjust the comment status for the get_comments() input  arguments, with help of the pre_get_comments action:
add_action( 'pre_get_comments', function( \WP_Comment_Query $query )
{
    // Only target edit-comments.php
    if( ! did_action( 'load-edit-comments.php' ) )
        return;

    // Only target users that can't publish posts
    if( current_user_can( 'publish_posts' ) )
        return;

    // Halt the query for pending comments
    if( 'hold' === $query->query_vars['status'] )
        $query->query_vars['status'] = 'non-existent';

    // Remove pending comments from the 'all' or '' status view
    if( in_array( $query->query_vars['status'], [ 'all', '' ], true ) )
        $query->query_vars['status'] = 'approve';
} );

where we target only the edit-comments.php page and modify the status to approve if it's empty or 'all' for users that can't publish posts.
Here we assign the comment status to a non existent status to remove the list of pending comments.
It can be a little confusing all the various status values for pending comments,  e.g.
hold, pending, moderated, '0'

depending if it's a label, a comment query variable or how it's stored in the database,
Modify the comments counts
All comments count here:

means the sum of the Approved + Pending comments counts.
When we change the comment query, like above, these comment status counts will not change. We might want to adjust that too.
Here's an example how we can adjust the comments counts via the wp_count_comments filter:
add_filter( 'wp_count_comments', 'wpse_count_comments', 10, 2 );

function wpse_count_comments( $counts, $post_id  )
{
    // Only target the backend
    if( !  is_admin() )
        return $counts;

    // Only target users that can't publish posts
    if( current_user_can( 'publish_posts' ) )
        return $counts;

    // Avoid infinite loop before calling wp_count_comments()
    remove_filter( current_filter(), __FUNCTION__ );
    $counts = wp_count_comments( $counts, $post_id  );
    add_filter( current_filter(), __FUNCTION__, 10, 2 );

    // Subract 'moderated' count from 'all' count
    $counts->all = $counts->all - $counts->moderated;

    // Set 'moderated' count to zero
    $counts->moderated = 0;

    return $counts;
}

This will also remove the counting number, for users that can't publish posts, from the admin menu here:

Modify the comment status links
Finally we might want to remove the status link for pending comments, for users that can't publish posts:
add_filter( 'comment_status_links', function( $status )
{
    if( ! current_user_can( 'publish_posts' ) )
        unset( $status['moderated'] );
    return $status;
} );

So it will become:

Hope it helps!

A: I have found this semi-solution, this code hide comment from comment moderation list, but it remove all comment also moderated comment, its ok for now =)
https://wordpress.stackexchange.com/questions/167250/prevent-contributor-to-show-comment-list
function filter_comments_by_contributor( $all_comments ) {
    // get the current logged in user
    $current_user = wp_get_current_user();

    if ( 0 == $current_user->ID ) {
        // Not logged in.
        return $all_comments;
    } else {
        // Logged in.

        // check if the logged-in user is a contributor
        if ( in_array( 'contributor', (array) $current_user->roles ) ) {

            // check if the user is on wp-admin backend,
            $screen = get_current_screen();
            if ( ! empty( $screen ) && 'edit-comments' == $screen->id ) {

                // get all posts by that contributor
                $args              = array(
                    'author'         => $current_user->ID,
                    'posts_per_page' => - 1,
                    'fields'         => 'ids'
                );
                $contributor_posts = get_posts( $args );

                // unset the comments given on posts other than his/her.
                foreach ( $all_comments as $key => $value ) {
                    if ( ! in_array( $value->comment_post_ID, $contributor_posts ) ) {
                        unset( $all_comments[ $key ] );
                    }
                }
            }

            return $all_comments;
        } else {
            return $all_comments;
        }
    }
}

if( is_user_logged_in() && !current_user_can('manage_options')) {
    add_filter( 'the_comments', 'filter_comment_by_contributor' );
}

A: I recommend you to use user role editor to have a full control on users roles in general and add some exceptions to specific users.


text:
Q: Remove grouping from dw at runtime Is it possible to remove a group or groups from a DW at runtime?

A: No, but you can collapse the group header and detail bands (e.g. dw.Modify ("datawindow.header.1.height=0")). This should get you close to the same effect.
Good luck,
Terry.

A: Instead of removing the group, you can swap out the whole DataWindow. To do this you make your grouped and ungrouped DataWindows so they have the same column definitions (one way is to use the same select). Retrieve your data into a DataStore. Then set whichever DataWindow you want to show and share from the DataStore. You can change the DataWindow after you've retrieved data, you just have to share the data again. This lets you have a completely different presentation for the grouped and ungrouped view. For example, your grouped DataWindow could be Freeform, and the ungrouped one could be Grid. One caveat is that you may have to make sure you have the same computed columns in the DataWindows you're sharing. I say may because the help says you have to, and I saw it for myself in older versions of PB. However we have a PB 11.2 app with many shared-to DataWindows that have computes that aren't in the source and they work fine. Your Mileage May Vary.


text:
Q: Escaping quotation marks in PHP I am getting a parse error, and I think it's because of the quotation marks over "time". How can I make it treat it as a whole string?
<?php
    $text1 = 'From time to "time" this submerged or latent theater in 'Hamlet'
    becomes almost overt. It is close to the surface in Hamlet's pretense of madness,
    the "antic disposition" he puts on to protect himself and prevent his antagonists
    from plucking out the heart of his mystery. It is even closer to the surface when
    Hamlet enters his mother's room and holds up, side by side, the pictures of the
    two kings, Old Hamlet and Claudius, and proceeds to describe for her the true
    nature of the choice she has made, presenting truth by means of a show.
    Similarly, when he leaps into the open grave at Ophelia's funeral, ranting in
    high heroic terms, he is acting out for Laertes, and perhaps for himself as well,
    the folly of excessive, melodramatic expressions of grief.";

    $text2 = 'From time to "time"';

    similar_text($textl, $text2, $p);
    echo "Percent: $p%";

The problem is that I can't manually add \ before every quotation mark. This is the actual text I need to compare.

A: Use a backslash as such
"From time to \"time\"";

Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';

The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"

As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;

A: Use htmlspecialchars(). Then quote and less / greater than symbols don't break your HTML tags~

A: Use the addslashes function:
 $str = "Is your name O'Reilly?";

 // Outputs: Is your name O\'Reilly?
   echo addslashes($str);

A: Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"
Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

A: $text1= "From time to \"time\"";

or
$text1= 'From time to "time"';

A: Either escape the quote:
$text1= "From time to \"time\"";

or use single quotes to denote your string:
$text1= 'From time to "time"';

A: You can use the PHP function addslashes() to any string to make it compatible


text:
Q: Double emulator I'm looking to install a PS3 OS on my XBOX360 so I can play both emulators. But mainly so I can use the PS3 to get online and play games without a subscription.
Is this possible and if so, how do I go about doing it?

A: The answer is no, for a number of reasons - I've listed a few here but this is just the tip of the iceberg, really.
You can't emulate current consoles on current consoles
There's a general rule of thumb that in order to fully emulate a console or other system you need a device that is several times more powerful than the emulated system. This is partly due to the complexity of completely emulating an entire hardware system at a software level (essentially recreating the hardware logic gate by gate).
Even if you don't mean emulation, the hardware is totally different
The PS3 OS is designed for the PS3 and the PS3 only. The architecture difference between it and the X360 is enormous and I highly doubt the OS even could run on the X360 without extensive changes.
The OS is proprietary and not available
There's no real way to get a copy of the PS3 OS (other than buying a PS3 of course, but that's no use in this case as you would need the source code or magically compiled binaries that magically run on the X360).
It would violate the X360 Terms of Agreement
This would definitely count as modding as your X360 and as such is not allowed under the licence that Microsoft provides. This may not be an issue for you personally but you should be aware of the implications. Of course, this is the least of your concerns as for this to be an issue you'd have to manage to get the thing done in the first place.


text:
Q: Lynx command line browser and the 'hosts' file I am building a small web app for my company and currently I have this weird issue:
I have 2 instances of the web app running, one accessible through the internet and another one for internal purposes and testing only. The internal version has a public IP address though.
When I try to access the public version of the app with the Lynx command line browser I get what I am supposed to get. So far so good. Now, when I make changes to the hosts file, so that when I try to access the app I would get the 'internal' version, what comes back is again the public version.
On top of that, there seems to be a problem only with my app. Any other website is correctly blocked or redirected when I make changes to the hosts file.
Any ideas?
UPDATE 1:
I tried this:
When running getent hosts I get the correct list from the /etc/hosts file. When I run getent hosts www.example.com though I get the 'outside' address, although the correction is clearly in place.


text:
Q: Is it possible to make a toggleable button that changes text when clicked I have made a JFrame that shows a start button, and changes to stop when clicked. How to make it so that it changes its text to start when stop is clicked. Here is the source code:
public class FRMCountdown extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FRMCountdown frame = new FRMCountdown();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public FRMCountdown() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton Start_Stop_btn = new JButton("Start");
        Start_Stop_btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Start_Stop_btn.setText("Stop");
            }

        });
        Start_Stop_btn.setBounds(10, 188, 89, 23);
        contentPane.add(Start_Stop_btn);
    }
}

A: Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Learning Swing with the NetBeans IDE section.
Swing was designed to be used with layout managers.  I used a FlowLayout to place one JButton.  Null layouts and absolute positioning lead to problems.
Java field names start with a lower case letter,  Java method names start with a lower case letter.  Java class names start with an upper case letter.
Here's the modified code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ToggleJButton {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ToggleJButton();
            }
        });
    }

    public ToggleJButton() {
        JFrame frame = new JFrame("Toggle JButton");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 100, 5, 100));

        JButton startStopButton = new JButton("Start");
        startStopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JButton button = (JButton) event.getSource();
                String text = button.getText();
                if (text.contentEquals("Start")) {
                    text = "Stop";
                } else {
                    text = "Start";
                }
                button.setText(text);
            }

        });
        panel.add(startStopButton);

        return panel;
    }

}


text:
Q: Errors "Module parse failed: Unexpected token (9:39)" when trying to use Mongoose in Electron+Vue+Vuetify app My Electron+Vue+Vuetify works fine. But when I tried to use Mongoose it started to get many errors of this kind:
    Module parse failed: Unexpected token (9:39)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|             method: "GET",
|             ...options,
>             hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1"),
|         });
|         req.on("error", (err) => {

 @ ./node_modules/@aws-sdk/credential-provider-imds/dist-es/index.js 5:0-59 5:0-59
 @ ./node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js
 @ ./node_modules/@aws-sdk/credential-providers/dist-es/index.js
 @ ./node_modules/mongoose/node_modules/mongodb/lib/deps.js
 @ ./node_modules/mongoose/node_modules/mongodb/lib/index.js
 @ ./node_modules/mongoose/lib/index.js
 @ ./node_modules/mongoose/index.js
 @ ./src/backend/database.js
 @ ./src/background.js
 @ multi ./src/background.js

I'm not using webpack, but anyway I went to the documentation suggested: https://webpack.js.org/concepts/#loaders. But this fix suggested there is not possible since I don't even have a webpack.config.js file, obviously, and neither the node modules listed in the error (mongoose and @aws-sdk) has.
Therefore, I have no idea why Mongoose is getting this errors.
I tried also do delete my node_modules and install everything again. Also tried audit fix in mongoose, (including force), and also nothing.
Any new ideas?


text:
Q: How to properly compress webpack chunks? I am already building a working web-app with a configuration that has gzip compression deactivated.
I use the HtmlWebpackPlugin to inject Vue stuff and generated chunks (js and css) into the main index.html.
The chunks are created by the splitChunks instruction of Webpack 4.
What I now want is to activate the CompressionWebpackPlugin in order to get my big output files smaller.
The compression plugin would do a perfect job if there would not be chunks. It creates a *.js.gz file for every chunk, BUT, it does not update the references in each chunk to other chunks.
Thus, the browser will not be able to find all of the needed files.
E.g. the index.html has one or two references to chunk1.js.gz and chunk2.js.gz, but inside chunk1 and chunk2 are many references to additional chunks, which cannot be found, because the references have the ending .js and the real files have the ending .js.gz.
How can I get the CompressionWebpackPlugin (or any other of the whole webpack settings and plugins) correctly configured, so that they will accordingly update the file references?
How can this be completely dynamic, so that I can even use the compression features of minimum-ratio or minimum-file-size? (Then some output chunks would be .js and some would be .js.gz, so some references have to be the first option, some references have to be the second option).
Other answers to similar questions said, one should compress server-side and not with webpack. However, for what reason does there exist the compression plugin then?
The setup is Vue, Webpack (Single page app), nginx, Django, Docker.
Here is my current configuration of Webpack:
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

const env = process.env.NODE_ENV === 'testing'
    ? require('../config/test.env')
    : require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
    mode: 'production',
    module: {
        rules: utils.styleLoaders({
            sourceMap: config.build.productionSourceMap,
            extract: true,
            usePostCSS: true
        })
    },
    devtool: config.build.productionSourceMap ? config.build.devtool : false,
    output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath('js/[name].[chunkhash].js'),
        chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    },
    plugins: [
        // extract css into its own file
        new MiniCssExtractPlugin({
            filename: utils.assetsPath('css/[name].[hash:7].css'),
            chunkFilename: utils.assetsPath('css/[id].[hash:7].css')
        }),
        // Compress extracted CSS. We are using this plugin so that possible
        // duplicated CSS from different components can be deduped.
        new OptimizeCSSPlugin({
            cssProcessorOptions: config.build.productionSourceMap
            ? { safe: true, map: { inline: false } }
            : { safe: true }
        }),
        // generate dist index.html with correct asset hash for caching.
        // you can customize output by editing /index.html
        // see https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            filename: process.env.NODE_ENV === 'testing'
                ? 'index.html'
                : config.build.index,
            template: 'index.html',
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
                // more options:
                // https://github.com/kangax/html-minifier#options-quick-reference
            },
            // necessary to consistently work with multiple chunks via CommonsChunkPlugin
            chunksSortMode: 'dependency',
            jsExtension: '.gz'
        }),
        // keep module.id stable when vender modules does not change
        new webpack.HashedModuleIdsPlugin(),
        // copy custom static assets
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, '../static'),
                to: config.build.assetsSubDirectory,
                ignore: ['.*']
            }
        ]),
    ],
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            chunks: 'all',
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                default: false,
                vendors: false,
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: 'all',
                    priority: 20,
                    name(module) {
                        // get the name. E.g. node_modules/packageName/not/this/part.js
                        // or node_modules/packageName
                        const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                        // npm package names are URL-safe, but some servers don't like @ symbols
                        return `npm.${packageName.replace('@', '')}`;
                    },
                },
                common: {
                    name: 'common',
                    minChunks: 2,
                    chunks: 'async',
                    priority: 10,
                    reuseExistingChunk: true,
                    enforce: true
                },
            },
        },
    },
})

if (config.build.productionGzip) {
    const CompressionWebpackPlugin = require('compression-webpack-plugin')

    webpackConfig.plugins.push(
        new CompressionWebpackPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.(js|css)(\?.*)?$/i,
            //threshold: 10240,
            //minRatio: 0.8,
            deleteOriginalAssets: true,
        }),
    )
}

if (config.build.bundleAnalyzerReport) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

A: On the specific question about why the compression plugin exists, the answer is that it's there to create compressed bundles at your server side.
Requests for JavaScript are made from the client browser with plain JS extensions. However the headers sent in the browser request include the type of responses which are acceptable to it. Look in the accept-encoding field and typically you'll see gzip and Brotli there.
Your server should receive the request for a JS file, but the code there should look in the header to work out which format to serve as the response. Your server should typically returns something compressed previously with the compression plugin which the client can cope with.


text:
Q: How to return preceding row value with column condition in SQL table? I have the below SQL table in which I need the most recent price only when condition type is 00:
ProductID ConditionType Date        Price
00001          01        2018-01-01  4.00
00001          01        2018-01-08  5.00
00001          00        2018-01-09  4.50
00001          01        2018-01-22  6.00
00001          00        2018-01-29  3.00

I have tried using a lag function but am having trouble with the partitions.
select
ProductID,ConditionType,Date,Price
,
case when conditiontype = 0 then
lag(Price,1) over (partition by ProductID,ConditionType order by Date asc)
else Price
end as lag
from TABLE

Output from query:
ProductID ConditionType Date        Price  Lag
00001          01        2018-01-01  4.00  4.00
00001          01        2018-01-08  5.00  5.00
00001          00        2018-01-09  4.50  null
00001          01        2018-01-22  6.00  6.00
00001          00        2018-01-29  3.00  4.50

Ideally we want to pull back the last price where condition type is 01 but I am having trouble getting this working.
Desired output:
ProductID ConditionType Date        Price  Lag
00001          01        2018-01-01  4.00  4.00
00001          01        2018-01-08  5.00  5.00
00001          00        2018-01-09  4.50  5.00
00001          01        2018-01-22  6.00  6.00
00001          00        2018-01-29  3.00  6.00

A: You can do this using first_value() and ignoring NULL values:
select t.*,
       first_value(case when conditionType = '00' then price end ignore nulls) over
           (partition by productId
            order by date desc
           ) as most_recent_00_price
from t;

EDIT:
I misunderstood the question.  I thought you wanted the most recent in the data.  You want the "running" most recent value.
The simplest way in SQL uses lag(ignore nulls), but that is not supported by Impala.  But you can use two window functions:
select t.*,
       max(case when date = date_00 then price end) over (partition by productId) as most_recent_00_price
from (select t.*,
             max(case when conditionType = '00' then date end) over (partition by productId order by date) as date_00
      from t
     ) t

A: You only need one partition clause in lag() :
select ProductID, ConditionType, Date, Price,
       (case when conditiontype = '00'
             then lag(Price) over (partition by ProductID order by Date)
             else Price
        end) as Lag
from TABLE;


text:
Q: When will Ubuntu One be available in German and other languages? Ubuntu One is a very good service. But at the moment nearly everything is in only available in english and not in other languages like german, french etc.. Also the terms of use are only english. Lots of people do not use Ubuntu One because they cannot understand the terms of use completely.

A: There are no plans to internationalise the website at the moment. Because the website contains a lot of commercial information, we can't have it translated by the community like the client.
Getting professional translations for dozens of languages is a huge undertaking (both in cost and effort).
We do, care about all users, but the translation of the website has not yet become a priority for us.
When it is, I'll make sure we announce it properly.


text:
Q: dosel/zalenium is executing the last created docker image instead of elgalu/selenium image I have already pulled elgalu/selenium and dosel/zalenium using the the docker pull.
Used the following code to start the zalenium:
docker run --rm -ti --name zalenium -d -p 4444:4444 -v /var/run/docker.sock:/var/run/docker.sock --privileged dosel/zalenium start --maxTestSessions 1 --desiredContainers 9

Here the dosel/zalenium starts correctly but the problem I am facing is that there are multiple docker images created after the latest elgalu/selenium version so, what zalenium is doing here is executing for selecting  the last created image whereas it should run the elgalu/selenium image.
I need help in fixing elgalu/selenium image as the permanent image which the dosel/zalenium will select everytime
I tried adding --seleniumImageName elgalu/selenium: latest at the last but it didn't work


text:
Q: Enable a javascript plugin on button press I have a webpage on which there a button.
On button press, I intent to embed a script in the head section of the page to enable a plugin. I can manually insert the snippet and my plugin but I want to be able to do this on button click itself to keep it as an optional element for my users.
What is the way to go about this?
As per @padde's query, the script looks like the following the way I include in my header:
<script type="text/javascript" src="http://code.abc.com/farfalla.js"></script>
<script type="text/javascript" src="http://code.abc.com/postmessage.js"></script>

A: Normally, you would simply put the script inside the <head> tags. Then, extract the initializing code from the included script and run it when the button was clicked.
Edit
You can also try this:
HTML
<button id="share-button">Share this</button>

JavaScript
dynamicCode = 'alert("script loaded");'
scriptLoaded = false;

buttonClicked = function(e) {
    if( !scriptLoaded ) {
        var script = document.createElement('script');
        script.text = dynamicCode;
        document.getElementsByTagName('head')[0].appendChild(script);
        scriptLoaded = true;
    }

    alert("thanks for sharing");
};

button = document.getElementById('share-button');
button.onclick=buttonClicked;

where you would load the dynamicCode with an Ajax call or whatever you like. The code is only loaded once. I've put together a jsfiddle for you, so you can try it out.

A: Use createElement() of javascript and add it to the DOM
Check the below link for more information : http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
If you are using jquery then you can use $.getScript to load the external js file.
$.getScript('filename.js',function(){
 //your code ...
});


text:
Q: Java swing: format content inside dialog I am having some issues trying to format JComponent locations inside of a dialog. I feel like this is a question that has an answer already but I had some issues finding information.
I've tried using setLocation on the elements, using a custom JOptionPane/JDialog (not sure if I did those correctly though) but they always ignore the formatting of the positions. and all the elements come out in a horizontal line

Ideally I would like the class names at the top, the 3 member lists in the middle and the button on the bottom.
I am creating the dialog like so:
JPanel createClass = new NewClass();
int result = JOptionPane.showConfirmDialog(GUI.this,
        createClass, "Create a class",JOptionPane.OK_CANCEL_OPTION);

and NewClass()(extends JPanel) looks like this:
//initializes the values
className = new JTextField(10);
superName = new JTextField(10);
publicMem = new DefaultListModel<String>();
protectedMem = new DefaultListModel<String>();
privateMem = new DefaultListModel<String>();
publicMem.addElement("Test");
publicMem.addElement("Test");
pubMemList = new JList(publicMem);
protMemList = new JList(protectedMem);
privMemList = new JList(privateMem);
pubMemList.setLocation(0,0);
newMember = new ButtonController(memberCommand);

//add Components to the JPanel
add(new JLabel("Class Name:"));
add(className);
add(Box.createHorizontalStrut(15));
add(new JLabel("Super Class Name:"));
add(superName);
add(new JLabel("\n"));
add(new JLabel("Public Members :"));
add(pubMemList);
add(new JLabel("Protected Members :"));
add(protMemList);
add(new JLabel("Private Members :"));
add(privMemList);
add(newMember);

So if anyone could point me in the right direction or to another similar post that would be greatly appreciated.

A: "Ideally I would like the class names at the top, the 3 member lists in the middle and the button on the bottom"
You could use a BorderLayout to achieve it. The following snippet may help you to get started:
    setLayout(new BorderLayout());

    //now add 3 panel as containers for top, center and bottom content
    JPanel top = new JPanel();
    add(top, BorderLayout.NORTH);
    JPanel center = new JPanel();
    add(center, BorderLayout.CENTER);
    JPanel bottom = new JPanel();
    add(bottom, BorderLayout.SOUTH);

    //manage layout and add content to top container
    top.setLayout(new FlowLayout());//actually it the default
    top.add(new JLabel("Class Name:"));
    JTextField className = new JTextField(10);
    top.add(className);
    top.add(new JLabel("Super Class Name:"));
    JTextField superName = new JTextField(10);
    top.add(superName);

    //todo manage layout and add content to center container
    //todo manage layout and add content to bottom container


text:
Q: How to increase Indy idFTP buffer? The OnFtpWork event fires really often for idFTP. IF it writes that often to disk then it will be a waste of time. Is there a way to increase the buffer so it will write to disk not often than once per second?

A: You can set the TIdFTP.IOHandler.SendBufferSize and TIdFTP.IOHandler.RecvBufferSize properties before performing a transfer.  They will be copied to the IOHandler used for the transfer connection.
Or you can use the TIdFTP.OnDataChannelCreate event to set the ADataChannel.IOHandler.SendBufferSize and ADataChannel.IOHandler.RecvBufferSize properties.
Or you can implement a TFileStream derived class that uses buffered file I/O internally, then you don't have to mess with TIdFTP's buffers.


text:
Q: jquery animate pushes div below before sliding I am using some jquery to slide a legend in and out next to a map. I have used this code before but now I am using it within a responsive framework so I am changing some things to percentages rather than pixels widths. Perhaps I have some things out of order in my script but the div containing the legend drops below the map while it animates back and forth.
Here's my script:
$(".hideLegendRight").click(function () {
    $(this).hide();
    $(".label").hide();
    $(".zoomTo").hide();
    $(".legendMenu").hide();
    $("#legendMap").animate({
        width: "0%"
    }, 500);
    $(".buttonsMap").animate({
        left: "25"
    }, 500);
    $("#wrapperMap").animate({
        width: "100%"
    }, 500, function () {
        $(".showLegendRight").show();
    });
    google.maps.event.trigger(map, 'resize');
});

$(".showLegendRight").click(function () {
    $(this).hide();
    $(".buttonsMap").animate({
        left: "0"
    }, 500);
    $("#legendMap").animate({
        width: "35%"
    }, 500);
    $("#wrapperMap").animate({
        width: "65%"
    }, 500, function () {
        $(".hideLegendRight").show();
        $(".legendMenu").show();
        $(".zoomTo").show();
        $(".label").show();
    });
    google.maps.event.trigger(map, 'resize');
});

And here's my jsfiddle

A: You are seeing this issue because of how html styling works. You won't fix this problem by merely changing some script value. Quite literally your issue is that as your #wrapperMap div grows, it doesn't leave enough room for you #legendMap div to be displayed. Not only that, but everything is automatically defaulting to a relative position. So when the #wrapperMap grows it displaces the #legendMap so that it is below it. Here's a good StackOverflow answer that outlines your problem.
Make div stay in top of parent
Pretty much you want to make the parent relative and the child absolute with a couple nuances to make it show up in the right spot. Here's the css I either added or altered to fix your problem.
.grid_12 {
  position:  relative;
}

#legendMap {
  position:  absolute;
  top:       0px;
  right:     0px;
  width:     35%;
  float:right;
  height:458px;
  background-color:#404040;
  z-index: -1;
  margin-bottom:20px;
  overflow:hidden;

}
fixed JSfiddle


text:
Q: Regular expression of validating text which contains certain special characters on condition I am trying to create a regular expression which will validate a text. Conditions are as follows:

*

*Must contain at least one alphanumeric character [A-Za-z0-9]

*Can contain allowed special character like [@#]. This is optional.

*No other characters are allowed other than the above mentioned chars[includes @ and #].

*Text length should be less than 8.

valid text: A, A@, @A, A@a@, @@@a etc
invalid text : @, @#, a:**, A@%, AAAAAAAAA(9 characters) etc
I have tried the below regex but it is partly working:
(?=.[\w])(?=.[@#])?.*{0,8}

A: ^(?=.*[a-zA-Z0-9])[A-Za-z0-9@#]{0,8}$

Try this.See demo.
The lookahead will make sure there is atleast one character.

A: Use the below regex in matches method.
"(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"

(?=.*?[A-Za-z0-9]) asserts that the string must contain atleast one letter or digit , so there must be a single character present in the match. That's why i defined [A-Za-z0-9@#]{1,8} instead of [A-Za-z0-9@#]{0,8}
String[] check = {"A", "A@", "@A", "A@a@", "@@@a", "@", "@#", "a:**", "A@%", "AAAAAAAAA"};
for(String i: check)
{

    System.out.println(i.matches("(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"));
}

Output:
true
true
true
true
true
false
false
false
false
false

A: You can use:
^(?=.*?[A-Za-z0-9])[@#A-Za-z0-9]{1,8}$

A: You can try regex like this :
public static void main(String[] args) {
    String s = "aaaaaaa";
    System.out.println(s.matches("(?=.*[A-Za-z0-9])[A-Za-z0-9@#]{1,7}"));
}

O/P :
true


text:
Q: How can screen recording software record the call audio of both the local person (on the mic) and the remote person (on the speakers)? I use SimpleScreenRecorder to record our group meetings from a Firefox screen of Jitsi. I use a USB headset and would like to record both the audio of what I say in my headset microphone and the audio of what others say that comes out of my headset earphones. I don't know how to do this and hope for guidance on audio configuration to enable me to do this, or some other options.
The program I'm using can be installed in the following way:
sudo add-apt-repository -y ppa:maarten-baert/simplescreenrecorder
sudo apt update
sudo apt -y install simplescreenrecorder

I have looked at the various audio streams using pavucontrol. When recording using the microphone of the headset, it is the "Clear Chat Comfort USB Headset Analog Mono" stream that is in use. When playing something using the earphones of the headset, it is the "Clear Chat Comfort USB Headset Analog Stereo" stream that is in use. I see no reactivity of the various streams labelled "monitor" and so on.
Is there some audio configuration I have not considered or implemented? What might be a solution to this?

A: You can route your microphone through your speakers. That might do the trick:

*

*How to hear my voice in speakers with a mic?
In summary:
pactl load-module module-loopback latency_msec=1


text:
Q: Want to subtract hour to hour, minutes to minutes, and seconds to seconds from between two dates <?php
    $ts='2011-04-13 23:00:00';
    $ts1='2011-04-14 15:45:00';
    echo $addtime = date("h:i:s", mktime(date("h", $ts1)- date("h", $ts),date("i", $ts1)- date("i", $ts),date("s", $ts1)- date("s", $ts),0,0,0));
?>

It gives a result but it is not correct in many cases.  How do I fix it?

A: Your expected result would be 16:45:00 for the given example, right? So you want the difference between the two given dates in hours:minutes:seconds.
<?php
    //initial strings
    $ts='2011-04-13 23:00:00';
    $ts1='2011-04-14 15:45:00';

    //converting to time
    $start = strtotime($ts);
    $end = strtotime($ts1);

    //calculating the difference
    $difference = $end - $start;

    //calculating hours, minutes and seconds (as floating point values)
    $hours = $difference / 3600; //one hour has 3600 seconds
    $minutes = ($hours - floor($hours)) * 60;
    $seconds = ($minutes - floor($minutes)) * 60;

    //formatting hours, minutes and seconds
    $final_hours = floor($hours);
    $final_minutes = floor($minutes);
    $final_seconds = floor($seconds);

    //output
    echo $final_hours . ":" . $final_minutes . ":" . $final_seconds;
?>

This gives me correct results. Hope I got your problem right!


text:
Q: findOneAndUpdate not updating the document and returning null I'm new to mongodb and mongoose.
Please help me out! I'm stuck in this problem that I describe below.
This is my code.
addressSchema and another schema for saving user id and the address
when i try to update the document im not getting any response from the below code.
but when i try 'find()' im getting the response.
 const addressSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        min: 2,
        max: 40
    },
    mobileNo: {
        type: String,
        required: true,
        trim: true
    },
    pincode: {
        type: String,
        required: true,
        trim: true
    },
    landmark: {
        type: String,
        required: true,
        trim: true
    },
    address: {
        type: String,
        required: true,
        trim: true
    },
    area: {
        type: String,
        required: true,
        trim: true
    },
    state: {
        type: String,
        required: true,
        trim: true
    },
    alternatePhoneNo: {
        type: String
    },
    addressType: {
        type: String,
        required: true,
        enum: [ 'home', 'work' ]
    }
})
        Schema for storing the address array and user ID

const userAddressSchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    address: [addressSchema]
}, { timestamps: true })

    I tried updating many ways but still cant update

//Code to update the document

const editAddress = (req, res) => {
    const { address } = req.body

    if(address) {
        UserAddress.findOne({ user: req.user._id })
        .exec((error, _userAddress) => {
            if(error) return res.status(400).json({ error })

            if(_userAddress) {
                UserAddress.findOneAndUpdate({ "_id": _userAddress._id,"address._id": address._id }, {
                    "$set": {
                        "address.$": {
                            "name": address.name,
                            "mobileNo": address.mobileNo,
                            "pincode": address.pincode,
                            "landmark": address.landmark,
                            "address": address.address,
                            "area": address.area,
                            "state": address.state,
                            "alternatePhoneNo": address.alternatePhoneNo,
                            "addressType": address.addressType
                        }
                    }
                })
                .exec((error, data) => {
                    if(error) return res.status(400).json({ error })
                    if(data) return res.status(201).json({ data })
                    console.log(error)
                    console.log(data)
                })
            }
        })
    }
}

Guys please help
Thanks in advance

A: Try awaiting the .findOneAndUpdate() function:
const editAddress = async (req, res) => {
    const { address } = req.body

    if(address) {
        await UserAddress.findOne({ user: req.user._id })
        .exec((error, _userAddress) => {
            if(error) return res.status(400).json({ error })

            if(_userAddress) {
                await UserAddress.findOneAndUpdate({ "_id": _userAddress._id,"address._id": address._id }, {
                    "$set": {
                        "address.$": {
                            "name": address.name,
                            "mobileNo": address.mobileNo,
                            "pincode": address.pincode,
                            "landmark": address.landmark,
                            "address": address.address,
                            "area": address.area,
                            "state": address.state,
                            "alternatePhoneNo": address.alternatePhoneNo,
                            "addressType": address.addressType
                        }
                    }
                })
                .exec((error, data) => {
                    if(error) return res.status(400).json({ error })
                    if(data) return res.status(201).json({ data })
                    console.log(error)
                    console.log(data)
                })
            }
        })
    }
}

Awaiting this fixed my error too.


text:
Q: Finding out the square's new coordinates after zooming in I have a canvas which is 600x600. The center of the canvas is at (300,300). I have a drawn a square at this coordinate. I have also drawn another square at (200,200). Both squares are 60x60 in size with the pivot at the centre.
Here is a screenshot below of the canvas:
http://prntscr.com/ggc7mn
Without any zoom, the zoom is set to the value of 1. After increasing the zoom level to 2.3349999999999973, the view looks this:
http://prntscr.com/ggc7xv
The center square's position is unchanged and still at the center at (300,300). Since the top left corner of the other square is at (0,0) in the second screen shot. I can calculate the center coordinates of the square by (length * zoom)/2 which is (60*2.33/2) = 69.9.
How can I calculate this if the square was not touching it's corner at (0,0) and if it was at any other position?

A: Here is a general angle of attack:
A zoom operation as you do is mathematically described as a so called "affine" transformation on each coordinate :
$$\left\{ \ \begin{array}{rcl}
x'=ax+b\\y'=cy+d
\end{array}\right. \ \ \ \iff \ \ \ \binom{x'}{y'}=\underbrace{\begin{pmatrix}
a & 0\\0&c
\end{pmatrix}}_{\text{scaling matrix}}\binom{x}{y}+\underbrace{\binom{b}{d}}_{translation}$$
with $(x,y)$ the old and $(x',y')$ the new coordinates, $a,b,c,d$ being constants that you can deduce from the images of 2 points (in order to have 4 equations in four unknowns): for example by tracking:

*

*the image of the south-east corner (a classical handle for windows resizing : keeping track of the initial and final mouse position).

*the image of the center of the window.
If it is a classical zoom, i.e. the length to width ratio is preserved: the shrinking/enlarging parameters will be the same for the $x$ and $y$ coordinates, i.e., $a=c.$
Edit: Fixed formula typos


text:
Q: how to check login I'm a beginner in android programming.So,I have no idea how to check my login by using PHP. NullPointerException is also appear.I don't know what should I do.Please help for login code.
That's my Jason code.
public void jsonen()
    {

        ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("userID","409"));

        String result = response.toString();// store the result returned by PHP script that runs MySQL query

        Log.i("response", response);
        try{
            JSONObject jArray = new JSONObject (result);
            for(int i=0;i<jArray.length();i++){

                  int status = jArray.getInt("requestStatus");
            }

    }
    catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

    }

    }

A: The code looks ok (looks horrible actually - well to many if statements and the goto mixed in) and I can't see anything obvious on a php side.
You are using global function db_connect() so make sure that this returns a link to DB.
Other then that you want to read about sql injection:
http://php.net/manual/en/security.database.sql-injection.php


text:
Q: React.js Display data from API by selecting multiple checkboxes I want to dynamically fetch data from an API by selecting API keys with checkbox value and show their properties in table.
Something like in these pictures:

Select values dynamically

Show values
{result.map((item) => {
  return (
    <div className="values">
      {item.[dynamic checkbox values]}
    </div>
  );
})}

How should I set checkbox dynamic values after item?
I appreciate your help.


text:
Q: Cv2.addWeighted returns "'Tuple' Object is not callable" error import cv2
import numpy as np
img1 = cv2.imread('3D-Matplotlib.png')
img2 = cv2.imread('mainsvmimage.png')

# add = img1 + img2
# add = cv2.add(img1, img2) # added all pixel values together
# (155, 211, 79) + 50, 170, 200 = 205, 381, 279
# which becomes (205, 255, 255) since 255 is the max

# add = cv2.add(img1//2, img2//2)
print(img1.shape)
print(img2.shape)

weighted = cv2.addWeighted(
    src1=np.array(img1),
    alpha=0.6,
    src2=np.array(img2),
    beta=0.4,
    gamma=0)

cv2.imshow('image', weighted)
cv2.waitKey(0)
cv2.destroyAllWindows()

Above is the code I am using based on this tutorial: https://pythonprogramming.net/image-arithmetics-logic-python-opencv-tutorial/
I am getting the following error when I try to run this in my IDE:
TypeError: 'tuple' object is not callable
I am running python version 3.6.4 on Windows 10 in Spyder version 3.2.8.
When I take the same code and I run it through the windows command prompt, it works, but it doesn't address the problem I am having in my IDE.


text:
Q: Is it possible multiple exception in an try block in c#? Is it possible to add multiple exception in an try block in c# ?
if possible,please provide with sample code
Thanks,
Santhu

A: you can provide multiple catch block block for a single try block like this:-
   try
   {
        //your code
   }
   catch(ExceptionClass e)
   {
       //code to handle exception
   }
   catch(ExceptionClass2 e)
   {
       //code to handle exception
   }
   catch(ExceptionClass3 e)
   {
       //code to handle exception
   }

but you always have to take care of hierarchy of Exception Classes. like for example, ExceptionClass should not be the Super class of ExceptionClass2 and ExceptionClass3.

A: Yes
try
{
 stuff()
}
catch (Exception1 e1)
{

}
catch (Exception2 e2)
{

}
finally
{

}

A: Remember to use exceptions from specific to more generics in different catch block
try {}
catch(FileNotFoundException fex) {}
catch(IOExceoption iex) {}
catch(Exception ex) {}
finally {}

A: You mean like this?
try
{
// Your code
}
catch(an exception)
{
}
catch(a different exception)
{
}
catch(any exception you want)
{
}


text:
Q: Android Studio 3.1 not showing build error details I have updated to Android Studio 3.1 and it doesn't show the details of error during compile time.
Suppose if I miss a semicolon somewhere or I haven't implemented a method of an interface, then it gives me this error all the time, but doesn't tell me what or where the error occurred!
All error details were perfectly shown in Studio 3.0. How do I see them in 3.1?
This is the message that I get every time an error occurs.
Compilation error. See log for more details

A: There is a toggle button just below the build button that will show the verbose build logs. Tap that and you should be able to see errors like before AS 3.1.

A: I don't know if that was your problem, but you should find your errors right there:

So you have to disclosure all these lines to get your errors, at the very bottom. If anyone have a better way to do that, I'm looking for too.

A: I have been having this error since I update my PC and updated to 3.1+ ( which was done a the same time ).  I was getting the tree view list of successes/ fails but when a fail occurred it just stopped,  it didn't actually list the errors in the tree.  I had to view the full debug logs to find out where any issues were happening.
I believe the issue is down to a space in my user name,  Android Studio downloading the SDK to the default location of "C:\Users\user name\AppData\Local\Android\sdk".  I spotted some of the config windows complaining about the space in that location,  so I've moved my SDK to "C:\Dev\Android\sdk" and now I see Java errors again at the bottom of the tree.


text:
Q: Removing duplicates over two columns in Excel Apologies if this has been asked before: there are numerous 'remove duplicates in Excel' questions, but I can't seem to find one that matches my exact problem.
I have two columns of customer e-mail addresses in Excel - one is a national list of about 8000, the other is localised, about 500. I'd like to remove the localised entries from the national list to avoid spamming the local recipients. How can I do this quickly?
(I am using the latest version of Excel)

A: Using the built-in function should work.

*

*Select both columns and choose Remove duplicates.

*On the Remove duplicates window uncheck the first column.

*Click OK and it should remove the duplicates from the
shorter list from the longer one.

Note: leaving both columns checked will result on no duplicates being found.

A: Your specific use case has a lightning-fast solution out in the wide fields beyond the excel gates. Open Venny : https://bioinfogp.cnb.csic.es/tools/venny/ . Copy-paste both your columns to two boxes. Click the appropriate part of the Venn diagram, and the list you need will be in the output. Copy-paste the output list back into your excel. Done.

Note: Venny is a client-side javascript. All the operations happen in your browser - no third party involved. You can Ctrl+S save it to your machine and open it when offline and it'll run.

A: Well, I'm assuming it removes duplicates sequentially: copy the 8000 below the 500 and then use the remove duplicates function for that single column. Copy from 501 and forward and you should have what you need.
(please test the initial assumption first)


text:
Q: Docker Ubuntu image missing prompt, color and completion? If I create a new Docker image based from ubuntu:14.04 image and run it with:
docker run -i --name="TEST" ubuntu:14.04 /bin/bash

then I will have a minimalistic Ubuntu with Bash running, but I won't get a prompt and the auto-completion for files/folders does not work. Also if I try to edit a file using vi then the terminal will corrupt everything shown on the screen, and arrows wont work either.
So how can I create a new image from ubuntu:14.04 where the 'normal' Bash-like functionality from a 'normal' terminal from the Ubuntu Desktop distribution is working so that I have the same colored prompt, auto-completion of files/folders are working and also vi works as expected?
EDIT: I'm running boot2docker on Windows if that makes any difference!?

A: You're missing -t flag to allocate a pseudo-tty for your container:
docker run -it --name="TEST" ubuntu:14.04 /bin/bash


text:
Q: Deep neural network gives a constant value as output I have implemented a neural network from scratch. I have taken random values as both input and output. When I use a single layer( with sigmoid activation) the network performs well. But when I increase the number of layers( No matter which activation I use), The network outputs a constant value.
I have attached the link to the full code and output for single layer and and a network with 2 hidden layers.
HyperParameter (relu,sigmoid,derRelu and derSigmoid are functions)
alpha= 0.01 #learning rate
m=10 #number of examples in training set
numberOfLayers=2 #including input and output layer
activations=[None,relu,sigmoid]
derActivations=[None,derRelu,derSigmoid]
neurons=[10,5,1]
numberOfIterations=1000

Initialization of parameters:
parameters=[]
parameters.append({})

for i in range(1,numberOfLayers):
    param={}
    param["W"]  =np.random.randn(neurons[i],neurons[i-1])*0.01
    param["b"]  =np.zeros((neurons[i],1))
    parameters.append(param)

These are some of the functions
def calculateZ(A,W,b):
Z=np.dot(W,A)+b
return Z

def derL(Y,A):
derL=np.true_divide(1-Y,1-A)-np.true_divide(Y,A)
return derL

def derW(dZ,A):
dW=np.dot(dZ,np.transpose(A))/m;
return dW

def derB(dZ):
db=np.sum(dZ,axis=1,keepdims=True)/m;
return db

def derZ(dW,dZ,Z,derActi):
dZNew=np.multiply(np.dot(np.transpose(dW),dZ),derActi(Z))
return dZNew

def forwardPropagation(layer):
    W=parameters[layer]["W"]    #current layer
    b=parameters[layer]["b"]    #current layer
    A=parameters[layer-1]["A"]  #previous layer

    Z=calculateZ(A,W,b)
    parameters[layer]["Z"]=Z    #current layer

    A=activations[layer](Z)
    parameters[layer]["A"]=A

def backwardPropagation(layer):
    Z=parameters[layer]["Z"]    #current layer

    if(layer==numberOfLayers-1):
        A=parameters[layer]["A"]
        dL=derL(Y,A)
        dZ=np.multiply(dL,derActivations[layer](Z))
    else:
        dZ=parameters[layer+1]["dZ"]  #next layer
        dW=parameters[layer+1]["dW"]  #next layer
        dZ=derZ(dW,dZ,Z,derActivations[layer])  #current layer

    parameters[layer]["dZ"]=dZ
    A=parameters[layer-1]["A"]  #previous layer

    dW=derW(dZ,A)               #current layer
    parameters[layer]["dW"]=dW
    db=derB(dZ)               #current layer
    parameters[layer]["db"]=db

Training
Y=np.random.randn(1,m)
Y=np.where(Y<0,0,1)

# genrating random input to test the code
parameters[0]["A"]=np.random.randn(neurons[0],m)
costs=[]

for i in range(numberOfIterations):
    for layer in range(1,numberOfLayers):
        forwardPropagation(layer)

    A=parameters[numberOfLayers-1]["A"]
    l=calculateLoss(Y,A)
    costs.append(l[0][0])

    for layer in range(numberOfLayers-1,0,-1):
        backwardPropagation(layer)

    for layer in range(1,numberOfLayers):
        updateParameters(layer)

Code
output with 0 hidden layer
output with 2 hidden layers
I am unable to find the problem.


text:
Q: Finding joint PMF given $X \sim Bernoulli(\frac{1}{3})$ and $Y = 4x-2$ If we know that $X  \sim Bernoulli(\frac{1}{3})$ and $Y = 4x-2$. Then, how can we find the set of $x,y$ coordinates, that give us non-zero probability, and write their probability?
I know that since $X  \sim Bernoulli(\frac{1}{3}) \implies$ $X = 0, 1$, and so the coordinates that give us non-zero probability would be $(0, -2)$ and $(1, 2)$. However, how can I find the probabilities corresponding to these coordinates? That is, $p_{X,Y}(0, -2)$ and $p_{X,Y}(1, 2)$?
Also, after doing some more digging I found that $p_{X,Y}(x,y) = p_{X}(x)$ when $Y = -2, 2$. Why is that the case?

A: As $Y=4X-2$, The probability of a specific coordinate $(x,y)$ is the same as the probability a $X=x$ if $y=4x-2$ and 0 anywhere else.
$$P(X=x,Y=y) = \left\{
\begin{array}{lcl}
P(X=x) & if & y=4x-2\\
0 & if & y\neq 4x-2
\end{array}\right.$$
Afterall, $$\left\{
\begin{array}{lcl}
P(X=0,Y=-2) & = & P(X=0) = 2/3\\
P(X=1,Y=2) & = & P(X=1) = 1/3\\
P(X=x,Y=y) & = & 0, \text{anywhere else}.
\end{array}\right.$$

A: The only values of $(X;Y)$ support are $(0;-2)$ and $(1;2)$ with probability $\frac{2}{3}$ and $\frac{1}{3}$, respectively


text:
Q: How to increase Spectrogram resolution? I have a time-domain signal that I want do a time-frequency analysis on it. When I tried the Spectrogram, I always get very low resolution.
For example:
I have a signal like this:
data = Table[
   Piecewise[{{Sin[2 \[Pi] 10 t], 0 <= t < 1/4}, {Sin[2 \[Pi] 25 t],
      1/4 <= t < 1/2}, {Sin[2 \[Pi] 50 t],
      1/2 <= t < 3/4}, {Sin[2 \[Pi] 100 t], 3/4 <= t <= 1}}], {t, 0,
    1, 1/1023}];
ListLinePlot[data, AspectRatio -> 0.2]

when I do a wavelet transform, I get a result that I can identify each frequency and their arrival time.
cwd = ContinuousWaveletTransform[data, GaborWavelet[6], {Automatic, 12}];
freq = (1023/(#*GaborWavelet[6]["FourierFactor"])) & /@ (Thread[{Range[8], 1}] /. cwd["Scales"]);
ticks = Transpose[{Range[Length[freq]], freq}];
WaveletScalogram[cwd, Frame -> True, FrameTicks -> {{ticks, Automatic}, Automatic},FrameLabel -> {"Time", "Frequency(Hz)"}, ColorFunction -> "RustTones"]

The wavelet transform is very good for me except I prefer a linear scale instead of a log scale. So I tried the Spectrogram.
Spectrogram[data, SampleRate -> 1023, ColorFunction -> "RustTones", FrameLabel -> {"Time", "Frequency(Hz)"}]

From the spectrogram I can barely see that there are four frequencies components, but the resolution is very low compared to the wavelet transform, and there seems be a lot of "noise" in it. So how can I use Spectrogram to plot a similar result as that of wavelet transform, a result that I can easily see the difference frequencies and their occurrence in time?
Edit:
Second example
data2 = {0.0000688553, 0.0000688557, 0.0000688564, 0.000068857, 0.0000688571, 0.0000688563, 0.0000688551, 0.000068854, 0.0000688539,0.0000688551, 0.0000688573, 0.0000688591, 0.0000688593, 0.0000688572, 0.0000688536, 0.0000688507, 0.0000688504, 0.0000688538, 0.0000688594, 0.0000688641, 0.0000688644, 0.0000688591, 0.0000688504, 0.0000688431, 0.0000688426, 0.0000688506, 0.0000688639, 0.0000688747, 0.0000688756, 0.0000688636, 0.0000688439, 0.0000688279, 0.0000688268, 0.0000688443, 0.0000688727, 0.0000688957, 0.0000688975, 0.0000688724, 0.0000688318, 0.0000687991, 0.0000687969, 0.0000688321, 0.0000688886, 0.0000689341, 0.0000689375, 0.000068889,0.0000688108, 0.0000687484, 0.0000687447, 0.0000688111, 0.0000689165, 0.0000690002, 0.0000690059, 0.0000689171, 0.0000687754, 0.000068664, 0.0000686589, 0.000068778, 0.0000689632, 0.000069108, 0.0000691159, 0.0000689611, 0.0000687182, 0.0000685311,0.0000685273, 0.0000687314, 0.0000690404, 0.0000692758, 0.0000692824, 0.0000690239, 0.0000686276, 0.000068331, 0.0000683373,0.0000686747, 0.0000691661, 0.0000695268, 0.0000695212, 0.0000691047, 0.0000684868, 0.0000680431, 0.0000680816, 0.0000686216, 0.0000693686, 0.0000698882, 0.0000698443, 0.0000691941, 0.0000682709, 0.0000676461, 0.0000677627, 0.0000686028, 0.0000696891, 0.0000703884, 0.000070254, 0.0000692688,0.0000679463, 0.0000671236, 0.0000674037, 0.0000686737, 0.0000701814, 0.0000710486, 0.0000707318, 0.0000692847, 0.0000674719, 0.0000664738, 0.0000670596, 0.0000689181, 0.0000709029, 0.0000718656, 0.0000712238, 0.0000691734, 0.0000668091, 0.0000657258, 0.000066827, 0.000069441, 0.0000718908, 0.0000727864, 0.0000716293, 0.0000688506, 0.0000659424, 0.0000649574, 0.0000668415, 0.0000703392, 0.0000731224, 0.0000736827, 0.0000718041, 0.0000682428, 0.0000649098, 0.0000643029, 0.000067249, 0.0000716496, 0.0000744731, 0.0000743462,0.0000715934, 0.0000673322, 0.0000638262, 0.0000639329, 0.0000681481, 0.0000732907, 0.0000757007, 0.0000745275, 0.0000708955, 0.0000662018, 0.0000628777, 0.0000639981, 0.0000695195, 0.000075033, 0.0000764844, 0.0000740176, 0.0000697294,0.0000650442, 0.0000622699, 0.0000645526, 0.0000711839, 0.0000765324, 0.0000765193, 0.0000727403, 0.0000682638, 0.0000641159, 0.0000621449, 0.000065499, 0.000072824, 0.0000774271, 0.0000756283, 0.0000708033, 0.000066779, 0.0000636471, 0.0000625116,0.0000665943, 0.000074074, 0.0000774592, 0.0000738344, 0.0000684751, 0.0000655744, 0.0000637559, 0.0000632316, 0.0000675249, 0.0000746401, 0.0000765622, 0.0000713567, 0.0000660968, 0.0000648676, 0.0000644101, 0.000064073, 0.0000680156,0.0000743922, 0.0000748728, 0.0000685322, 0.0000639731, 0.0000647345, 0.0000654567, 0.0000648017, 0.0000679187, 0.0000733889, 0.0000726689, 0.0000657091, 0.0000622946, 0.0000651115, 0.0000666921, 0.0000652615, 0.0000672442, 0.0000718318, 0.0000702735, 0.0000631592, 0.0000611172, 0.0000658463, 0.0000679338, 0.0000654099, 0.0000661311, 0.0000699868, 0.0000679712, 0.0000610429, 0.0000603915, 0.0000667595, 0.0000690611, 0.0000653029, 0.0000647858, 0.0000681115, 0.0000659659, 0.0000594197, 0.0000600132, 0.0000676898, 0.0000700163, 0.0000650527, 0.000063423, 0.0000664129,0.0000643775, 0.0000582827, 0.0000598674, 0.0000685134, 0.000070784, 0.0000647821, 0.0000622261, 0.0000650355, 0.0000632614,0.0000575952, 0.000059858, 0.0000691461, 0.0000713679, 0.0000645938, 0.0000613302, 0.000064069, 0.0000626336, 0.0000573173,0.0000599219, 0.0000695408, 0.0000717756, 0.0000645558, 0.0000608195, 0.0000635588, 0.0000624885, 0.0000574204, 0.0000600333, 0.0000696834, 0.0000720124, 0.0000646977, 0.0000607281, 0.0000635126, 0.0000628061, 0.0000578888, 0.0000602007, 0.0000695902, 0.0000720824, 0.0000650125, 0.0000610423, 0.0000639015, 0.0000635503, 0.0000587147, 0.0000604608, 0.0000693062, 0.0000719916, 0.000065463, 0.0000617039,0.0000646594, 0.000064664, 0.0000598881, 0.0000608677, 0.0000689002, 0.0000717529, 0.0000659909, 0.0000626183, 0.0000656854, 0.0000660624, 0.0000613839, 0.0000614786, 0.0000684577, 0.0000713905, 0.0000665298, 0.0000636677, 0.0000668497, 0.0000676302, 0.0000631474, 0.000062335, 0.0000680682,0.0000709408, 0.0000670184, 0.0000647289, 0.0000680081, 0.0000692241, 0.0000650845, 0.0000634439, 0.0000678097, 0.0000704504, 0.0000674126, 0.000065693, 0.0000690214, 0.0000706853,0.00006706, 0.000064764, 0.0000677327, 0.0000699684, 0.0000676912, 0.000066482, 0.0000697781, 0.0000718607, 0.0000689098, 0.0000662045,0.0000678498, 0.0000695389, 0.0000678562, 0.0000670585, 0.0000702138, 0.000072631, 0.0000704663, 0.0000676364, 0.0000681344,0.0000691935, 0.0000679274, 0.0000674255, 0.0000703228, 0.0000729367, 0.0000715913, 0.0000689162, 0.0000685272, 0.0000689492, 0.0000679364, 0.0000676184, 0.0000701554, 0.000072794,0.0000722085, 0.0000699157, 0.0000689494, 0.0000688079, 0.0000679212, 0.0000676936, 0.0000698037, 0.0000722933, 0.0000723258, 0.0000705539, 0.0000693212, 0.0000687577, 0.00006792, 0.0000677163, 0.0000693786, 0.0000715782, 0.0000720359, 0.0000708189, 0.0000695815, 0.0000687748, 0.000067962, 0.0000677458,0.0000689833, 0.0000708076, 0.0000714897, 0.0000707694, 0.0000697032, 0.0000688285, 0.0000680579, 0.0000678211, 0.0000686895, 0.0000701136, 0.0000708499, 0.00007051, 0.0000696956, 0.0000688882, 0.000068197, 0.000067952, 0.0000685249, 0.0000695739, 0.0000702467, 0.0000701544, 0.0000695939, 0.0000689322, 0.0000683544, 0.000068123, 0.0000684773, 0.0000692078, 0.0000697549,0.0000697941, 0.0000694432, 0.0000689511, 0.0000685038, 0.0000683059, 0.000068511, 0.0000689924, 0.0000693973, 0.0000694848,0.0000692835, 0.0000689472, 0.000068627, 0.0000684739, 0.0000685852, 0.0000688856, 0.0000691611, 0.0000692488, 0.0000691419, 0.0000689291, 0.0000687172, 0.0000686102, 0.0000686674, 0.0000688449, 0.0000690179, 0.0000690851, 0.0000690317, 0.0000689062, 0.0000687771, 0.0000687096, 0.0000687381, 0.0000688373, 0.0000689375, 0.0000689807, 0.0000689548, 0.0000688857, 0.0000688133, 0.0000687752, 0.0000687896, 0.0000688418, 0.0000688953, 0.0000689191, 0.0000689065, 0.0000688709, 0.0000688339, 0.0000688149, 0.0000688224, 0.0000688483, 0.0000688742, 0.0000688855, 0.0000688791, 0.000068862, 0.0000688449, 0.0000688367, 0.0000688408,0.0000688527, 0.0000688641, 0.0000688686, 0.0000688653, 0.0000688577, 0.0000688507, 0.0000688478, 0.0000688499, 0.000068855,0.0000688594, 0.0000688608, 0.0000688591, 0.0000688561, 0.0000688535, 0.0000688527, 0.0000688538, 0.0000688558, 0.0000688573, 0.0000688576, 0.0000688568, 0.0000688558, 0.000068855,0.0000688549, 0.0000688554, 0.000068856, 0.0000688564, 0.0000688564, 0.0000688561, 0.0000688557, 0.0000688556, 0.0000688556, 0.0000688558, 0.000068856, 0.0000688561, 0.0000688561,0.000068856, 0.0000688559, 0.0000688559, 0.0000688559, 0.0000688559, 0.000068856, 0.000068856};

cwd=ContinuousWaveletTransform[data2, GaborWavelet[6], {Automatic, 12}]
WaveletScalogram[cwd, ColorFunction -> "RustTones"]

Spectrogram[data2, ColorFunction -> "RustTones"]

A: The Spectrogram function also allows you to alter the window length, overlap and apply a windowing function to your data segment before FFT. You'll get better results if you utilize those (which requires some knowledge of DSP and your specific problem) instead of using the default parameters and the rectangle window.
For instance, the following shows the frequencies distinctly:
Spectrogram[data, 128, 64, BlackmanWindow, SampleRate -> 1023,
    FrameLabel -> {"Frequency(Hz)", "Time"}]

A: Urghhh ... I hate those "RustTones"... Nevertheless ^o^
sa = SpectrogramArray[data2];
ListDensityPlot[Transpose@Abs@sa, ColorFunction -> "DeepSeaColors",
                AspectRatio -> 1/2, Frame -> None]

ListDensityPlot[Transpose@Abs@sa, ColorFunction -> Hue,
                AspectRatio -> 1/2, Frame -> None]

A: Actually, we can get linear scale rather than log scale using wavelet transform, using the "LinearScalogramFunction" property of a ContinuousWaveletData object.
This is the default wavelet scalogram:
sampleRate = 1023;
data = Table[
   Piecewise[{{Sin[2 π 10 t], 0 <= t < 1/4}, {Sin[2 π 25 t],
      1/4 <= t < 1/2}, {Sin[2 π 50 t],
      1/2 <= t < 3/4}, {Sin[2 π 100 t], 3/4 <= t <= 1}}], {t, 0,
    1, 1/sampleRate}];
cwd = ContinuousWaveletTransform[data,
   DGaussianWavelet[5], {Automatic, 12}, SampleRate -> sampleRate];
WaveletScalogram[cwd, ColorFunction -> "RustTones"]

This uses the "LinearScalogramFunction" property to get a linear function and then plot the linear scale function using DensityPlot
f = cwd["LinearScalogramFunction"];
scaleToFrequency[
   s_] = (cwd["SampleRate"]/(s*cwd["Wavelet"]["FourierFactor"]));
DensityPlot[Abs[f[x, scaleToFrequency[y]]], {x, 0, 1}, {y, 2, 100},
 PlotPoints -> {300, 100}, ColorFunction -> "RustTones",
 ClippingStyle -> Automatic,
 FrameLabel -> {"Time (second)", "Frequency (Hz)"}]


text:
Q: Show that $\mathbb P^n$ has a cell decomposition... I dont know were to start here. I got a solution from my teacher but I dont get it at all, maybe another point of view can make understand the proof better.

A: Let $\mathbb{P}^0$ be a point, then $\mathbb{P}^1 \cong S^1$ is a 1-disk (closed interval) with its boundary glued to $\mathbb{P}^0$.
$\mathbb{P}^2$ is just a 2-disk with its boundary glued with some function to $\mathbb{P}^1$ and so on, you just need to come up with the induction and the functions $f: \partial D^{n+1} \cong S^n \to \mathbb{P}^n$ to get an isomorphism $\mathbb{P}^{n+1} = \mathbb{P}^n \cup_f D^{n+1}$.


text:
Q: Code calculates the sum of a range of rows but the average row calculation then included the sum row I'm quite inexperienced with VBA
My code calculates the sum of a range of rows (dynamic) and places these values 2 rows beneath the last row. Beneath that I want the average values. The verage calculation  is including the sum row and is therefore doubling all the average values
Dim r As Range, j As Long, k As Long
j = Sheets(2).Range("A1").End(xlToRight).Column

'This adds up the totals on the Sorted1 sheet
For k = 9 To j
Set r = Sheets(2).Range(Sheets(2).Cells(1, k), Sheets(2).Cells(1, k).End(xlDown))
r.End(xlDown).Offset(2, 0) = WorksheetFunction.Sum(r)
Next k

Else

MsgBox ("There is no data at column D")
End If

Application.ScreenUpdating = True

Dim mySheet As Worksheet
Dim myColumn As Range
Dim myDataSet As Range
Dim myAvg As Double
Dim LastRow as long

Set mySheet = ActiveSheet
For Each myColumn In mySheet.Range("I:Q").Columns
lastRow = mySheet.Cells(mySheet.Rows.Count, myColumn.Column).End(xlUp).row
myAvg = Application.WorksheetFunction.Average(myColumn.Rows(1).Resize(lastRow, 1))
myColumn.Rows(lastRow).Offset(1, 0).Value = myAvg
Next

I'm trying to find a way of excluding the Sum row from being a part of the average row calculations.
End Sub


text:
Q: preg_replace and Regular expression in PHP Could you please help me? I don't understand why do I get this error.

Warning: preg_replace(): Unknown modifier 'h'

$data_proces="<link>http://news.abc.com/news/url?sa=t&fd=R&ampkkk&url=http://example.com/abc<link>
$find_delete="<link>http:\/\/news\.abc\.com\/news\/url\?sa=.+url=";
    $replace_x="<link>";
    $data_process= preg_replace($find_delete,$replace_x, $data_process);

A: You miss delimetes in $find_delete. It should be:
$data_process="<link>http://news.abc.com/news/url?sa=t&fd=R&ampkkk&url=http://example.com/abc<link>";
$find_delete="/<link>http:\/\/news\.abc\.com\/news\/url\?sa=.+url=/";
              ^                                                   ^
$replace_x="<link>";
echo preg_replace($find_delete,$replace_x, $data_process);

A: Easy. In PHP, you have to start and end the regex string with /. After the end / you can put some modifier flag. Read this for more understanding. http://www.rexegg.com/regex-modifiers.html
So you code should be:
$find_delete="/<link>http:\/\/news\.abc\.com\/news\/url\?sa=.+url=/";

A: Use delimiters at start and end. It is advisable to choose a character which does not occur in the pattern, for example:
$find_delete = "#<link>http://news\\.abc\\.com/news/url\\?sa=[^;]+;url=#";