text:
Q: Problem in executing Query of resultset Object for JDBC Connectivity I am facing the GRAND PROBLEM in executing query from resultset object for mu JDBC work....
please help
problem appears in this statement
resultset = statement.executeQuery(query);
this gives this error
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected end of statement:  required: (
    at net.ucanaccess.jdbc.UcanaccessStatement.executeQuery(UcanaccessStatement.java:218)
    at DB.AuthorsManager.viewAuthor(AuthorsManager.java:26)
    at UI.Client.main(Client.java:268)
Caused by: java.sql.SQLSyntaxErrorException: unexpected end of statement:  required: (
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCStatement.executeQuery(Unknown Source)
    at net.ucanaccess.jdbc.UcanaccessStatement.executeQuery(UcanaccessStatement.java:216)
    ... 2 more
Caused by: org.hsqldb.HsqlException: unexpected end of statement:  required: (
    at org.hsqldb.error.Error.parseError(Unknown Source)
    at org.hsqldb.ParserBase.unexpectedTokenRequire(Unknown Source)
    at org.hsqldb.ParserBase.readThis(Unknown Source)
    at org.hsqldb.ParserDQL.XreadTableFunctionDerivedTable(Unknown Source)
    at org.hsqldb.ParserDQL.readTableOrSubquery(Unknown Source)
    at org.hsqldb.ParserDQL.XreadTableReference(Unknown Source)
    at org.hsqldb.ParserDQL.XreadFromClause(Unknown Source)
    at org.hsqldb.ParserDQL.XreadTableExpression(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
    at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
    at org.hsqldb.Session.executeDirectStatement(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 5 more

This is Authors Manager Class whose method viewAuthor is facing error
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AuthorsManager {
    public static  void viewAuthor(){
        int col1 = 0;
        String col2=null;
        DBConnect dbconnect = new DBConnect();
        dbconnect.getConnection("this.accdb");
        Statement statement = dbconnect.getStatement();
        String query = "SELECT * from Table";
        try {
            ResultSet resultset=null;
            resultset = statement.executeQuery(query);
            col1 = resultset.getInt("id");
        }
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            DBConnect.disconnect();
        }
    }
}

and this is DBConnect Class which is Connecting and giving statement object to AuthorsManager class
DBConnect Class

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnect {

    private static Connection connection = null;
    private static Statement statement = null;

    public static void getConnection(String path) {

        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            connection = DriverManager.getConnection("jdbc:ucanaccess://" + path);
            statement  = connection.createStatement();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

    }

    public static Statement getStatement() {
        // TODO Auto-generated method stub
        return statement;
    }

    public static void disconnect() {
        try {
            connection.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


text:
Q: How to remove flicker from exit reveal animation and make it reveal from point of touch What I want to achieve are these:

*

*When an item in the recyclerView is clicked, the details activity should reveal, starting from the point that my finger touches the
screen.

*When I touch the up arrow button or back button, the details activity should finish with a circular reveal and stop at the point where
my finger touched the screen initially.
MY CODE:
MyRecyclerViewHolder
private OnGridItemClickedListener itemClickedListener

    public MyRecyclerViewHolder(View itemView,  OnGridItemClickedListener itemClickedListener) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        this.itemClickedListener = itemClickedListener;
        rippleView.setOnTouchListener(touchListener);
    }

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                itemClickedListener.onItemClick(getAdapterPosition(), null, (int)event.getY(), (int)event.getX());
            }
            return true;
        }
    };

MyFragment
// Removed irrelevant codes
 MyAdapter adapter = new MyAdapter(itemsList, true);
 recyclerView.setLayoutManager(new GridAutoFitLayoutManager(getActivity(), MyConvert.dpToPx(150, getActivity())));
 recyclerView.setAdapter(adapter);
 recyclerView.setHasFixedSize(true);

 adapter.setOnGridItemClickedListener(new OnGridItemClickedListener() {
     @Override
     public void onItemClick(int position, String stringId, int y, int x) {
         launchMyDetailsActivity(position, y, x);
     }
 });

 private void launchMyDetailsActivity(int index, int y, int x) {
     Intent intent = new Intent(getActivity(), MyDetailsActivity.class);
     intent.putExtra(Keys.EXTRA_Y, y);
     intent.putExtra(Keys.EXTRA_X, x);
     startActivity(intent);
 }

MyDetailsActivity
// Removed irrelevant codes

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_grid_details);
     ButterKnife.bind(this);
     setSupportActionBar(toolbar);
     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     setViewListeners();
     startEnterTransition();
 }

 private void startEnterTransition () {
     coordinatorLayout.post(new Runnable() {
         @Override
         public void run() {
             int x = getIntent().getIntExtra(Keys.EXTRA_X, 0);
             int y = getIntent().getIntExtra(Keys.EXTRA_Y, 0);

             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && x != 0 && y != 0) {
                 // get the final radius for the clipping circle
                 int finalRadius = Math.max(coordinatorLayout.getWidth(), coordinatorLayout.getHeight()) / 2;

                 // create the animator for this view (the start radius is zero)
                 Animator anim = ViewAnimationUtils.createCircularReveal(coordinatorLayout, x, y, 0, finalRadius);

                 // make the view visible and start the animation
                 coordinatorLayout.setVisibility(View.VISIBLE);
                 anim.start();
             }
         }
     });
 }

 private void startExitTransition () {
     int x = getIntent().getIntExtra(Keys.EXTRA_X, 0);
     int y = getIntent().getIntExtra(Keys.EXTRA_Y, 0);

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && x != 0 && y != 0) {
         int initialRadius = coordinatorLayout.getWidth() / 2;

         Animator anim = ViewAnimationUtils.createCircularReveal(coordinatorLayout, x, y, initialRadius, 0);

         anim.addListener(new AnimatorListenerAdapter() {
             @Override
             public void onAnimationEnd(Animator animation) {
                 super.onAnimationEnd(animation);
                 coordinatorLayout.setVisibility(View.INVISIBLE);
                 supportFinishAfterTransition();
             }
         });

         anim.start();

     } else {
         supportFinishAfterTransition();
     }
 }

 @Override
 public void onBackPressed() {
     startExitTransition();
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
     switch (item.getItemId()) {

         case android.R.id.home:
             startExitTransition();
             return true;
     }

     return super.onOptionsItemSelected(item);
 }

Problems

*

*The reveal animation starts from the top-left of the screen, close to the burger icon even when the item I clicked is close to the bottom
of the screen. The same goes for the exit animation, it stops at the top-left of the screen

*After the exit animation ends, the screen flashes, it doesn't always happen but it does happen.
Implemented solution
I have tried this in the viewHolder: itemView.getX() and itemView.getY(), itemView.getRight() and itemView.getTop(). These appeared
   to solve number one problem above but the point of entry and exit of the animations are always off from the point of the recyclerView item.
Please how do I fix numbers  and 2 problems above?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replacing text with StoryRange on Word VBA makes it briefly unresponsive I've used the following code to find and replace text on every storyrange, although I'm looking specifically for footers/headers and mainbody.
For Each myStoryRange In ActiveDocument.StoryRanges
    If myStoryRange.StoryType = wdPrimaryFooterStory Then

        myStoryRange.Find.Execute FindText:=footerfindreplace.Item(i).FND, Forward:=True, ReplaceWith:=footerfindreplace.Item(i).replc, Wrap:=wdFindContinue, replace:=wdReplaceAll

    End If
    If myStoryRange.StoryType = wdFirstPageFooterStory Then
        myStoryRange.Find.Execute FindText:=footerfindreplace.Item(i).FND, Forward:=True, ReplaceWith:=footerfindreplace.Item(i).replc, Wrap:=wdFindContinue, replace:=wdReplaceAll
    End If

    If myStoryRange.StoryType = wdEvenPagesFooterStory Then
        myStoryRange.Find.Execute FindText:=footerfindreplace.Item(i).FND, Forward:=True, ReplaceWith:=footerfindreplace.Item(i).replc, Wrap:=wdFindContinue, replace:=wdReplaceAll

    End If

Next myStoryRange

It worked allright for the footers and if the document had only one section.
However I have documents with more than one section of course, and I'd rather go trough all the document. So I found a different approach:
With ActiveDocument
  For Each Rng In .StoryRanges
    On Error Resume Next
    With Rng.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Format = False
      .Forward = True
      .Wrap = wdFindContinue
      .Text = footerfindreplace.Item(i).FND
      .Replacement.Text = footerfindreplace.Item(i).replc
      .MatchCase = True
      .Execute replace:=wdReplaceAll
    End With
    On Error GoTo 0
  Next
  For Each Sctn In .Sections
    For Each HdFt In Sctn.Headers
      With HdFt
        If .LinkToPrevious = False Then
          With .Range.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Format = False
            .Forward = True
            .Wrap = wdFindContinue
            .Text = footerfindreplace.Item(i).FND
            .Replacement.Text = footerfindreplace.Item(i).replc
            .Execute replace:=wdReplaceAll
          End With
        End If
      End With
    Next
    For Each HdFt In Sctn.Footers
      With HdFt
        If .LinkToPrevious = False Then
          With .Range.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Format = False
            .Forward = True
            .Wrap = wdFindContinue
            .Text = footerfindreplace.Item(i).FND
            .Replacement.Text = footerfindreplace.Item(i).replc
            .Execute replace:=wdReplaceAll
          End With
        End If
      End With
    Next
  Next
    End With

This works perfectly but has something I dislike, the word becomes unresponsive for about 10 seconds, regardless of the document. I also found there are 17 types of storyranges, and maybe that's the reason why it takes so long.
I know at least that with headers and footers (which are 6 of them) I can use the condition .Exists = true or false, to skip them. But that doesn't improve the result a lot.
I only have 5 words for replacement, Why does it become unresponsive? Is there a way to make it smooth?
Thanks for any help.
Update:
Upon reading the comments, I've tried the following with no avail
With ActiveDocument.StoryRanges(1).Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Format = False
      .Forward = True
      .Wrap = wdFindContinue
      .Text = footerfindreplace.Item(i).FND
      .Replacement.Text = footerfindreplace.Item(i).replc
      .MatchCase = True
      .MatchAllWordForms = False
      .MatchWholeWord = False
      .MatchWildcards = False
      End With

  For Each Rng In ActiveDocument.StoryRanges
    On Error Resume Next
    With Rng.Find
    .Text = footerfindreplace.Item(i).FND
      .Replacement.Text = footerfindreplace.Item(i).replc
      .Execute replace:=wdReplaceAll
    End With
    On Error GoTo 0
  Next
  For Each Sctn In ActiveDocument.Sections
    For Each HdFt In Sctn.Headers
      With HdFt
        If .LinkToPrevious = False Then
        If HdFt.Exists = True Then
          With .Range.Find
          .Text = footerfindreplace.Item(i).FND
      .Replacement.Text = footerfindreplace.Item(i).replc
            .Execute replace:=wdReplaceAll
          End With
          End If
        End If
      End With
    Next
    For Each HdFt In Sctn.Footers
      With HdFt
        If .LinkToPrevious = False Then
        If HdFt.Exists = True Then
          With .Range.Find
          .Text = footerfindreplace.Item(i).FND
      .Replacement.Text = footerfindreplace.Item(i).replc
            .Execute replace:=wdReplaceAll
          End With
          End If
        End If
      End With
    Next
  Next

If I dont place
  .Text = footerfindreplace.Item(i).FND
  .Replacement.Text = footerfindreplace.Item(i).replc

In every loop, it will not replace. Also the update display is already false.
Can anyone help?
Update:
Recently I tried to search every section inside mystory ranges, hoping to filter out the order..
For Each storyrang In ActiveDocument.StoryRanges
For Each Sctn In storyrang.Sections
For Each rang In Sctn.Ranges
With rang
For ii = 1 To footerfindreplace.count
  Call RngFnd(.Range, footerfindreplace.Item(i).FND, footerfindreplace.Item(i).replc) 'find and replace text in the given range
  Next ii
  End With
  Next
  Next
  Next

The result however remains not good

A: Your code is lacking context - specifically regarding footerfindreplace.Item(i).FND and footerfindreplace.Item(i).replc. You're code is also processing all storyranges (which includes headers & footers), then processing headers & footers again by Section.
If footerfindreplace.Item(i).FND and footerfindreplace.Item(i).replc represent a single call to the document, you might use code like:
Sub Demo()
Application.ScreenUpdating = False
Dim Sctn  As Section, HdFt As HeaderFooter
With ActiveDocument
  Call RngFnd(.Range, footerfindreplace.Item(i).FND, footerfindreplace.Item(i).replc)
  For Each Sctn In .Sections
    For Each HdFt In Sctn.Headers
      With HdFt
        If .LinkToPrevious = False Then
          Call RngFnd(.Range, footerfindreplace.Item(i).FND, footerfindreplace.Item(i).replc)
        End If
      End With
    Next
    For Each HdFt In Sctn.Footers
      With HdFt
        If .LinkToPrevious = False Then
          Call RngFnd(.Range, footerfindreplace(i).FND, footerfindreplace(i).replc)
        End If
      End With
    Next
  Next
End With
Application.ScreenUpdating = True
End Sub

Sub RngFnd(Rng As Range, StrFnd As String, StrRep As String)
With Rng.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Format = False
  .Forward = True
  .Wrap = wdFindContinue
  .Text = StrFnd
  .Replacement.Text = StrRep
  .MatchCase = True
  .Execute Replace:=wdReplaceAll
End With
End Sub

Alternatively, if you're processing multiple footerfindreplace items, you might use code like:
Sub Demo()
Application.ScreenUpdating = False
Dim Sctn  As Section, HdFt As HeaderFooter
With ActiveDocument
  Call RngFnd(.Range, footerfindreplace)
  For Each Sctn In .Sections
    For Each HdFt In Sctn.Headers
      With HdFt
        If .LinkToPrevious = False Then
          Call RngFnd(.Range, footerfindreplace)
        End If
      End With
    Next
    For Each HdFt In Sctn.Footers
      With HdFt
        If .LinkToPrevious = False Then
          Call RngFnd(.Range, footerfindreplace)
        End If
      End With
    Next
  Next
End With
Application.ScreenUpdating = True
End Sub

Sub RngFnd(Rng As Range, ArrFndRep)
Dim i As Long
With Rng.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Format = False
  .Forward = True
  .MatchCase = True
  .Wrap = wdFindContinue
  For i = 0 To UBound(ArrFndRep)
    .Text = ArrFndRep(i).FND
    .Replacement.Text = ArrFndRep(i).replc
  .Execute Replace:=wdReplaceAll
  Next
End With
End Sub

In either case, though, it's hardly apparent why you'd be processing something described as footerfindreplace in either the document body or its headers...

A: I'm posting this years later in case it helps others coding for StoryRanges.
I've got a similar issue and the OP's code gave me a start, so this is my Thank you.
The OP wanted to replace arbitrary text in MainTextStory, and in all Headers & Footers. His original code failed if there was more than a single Section.
The vital element is that Help defines StoryRanges as a Collection of Ranges.
Story Ranges can be chained together by the NextStoryRange property
This code iterates the entire document text just once
The Find Replace is the OP's code, but I've added a For loop for clarity
For Each myStoryRange In ActiveDocument.StoryRanges
    Do
        For i = lbound(footerfindreplace.Item) to Ubound(footerfindreplace.Item)
            myStoryRange.Find.Execute FindText:=footerfindreplace.Item(i).FND, Forward:=True, ReplaceWith:=footerfindreplace.Item(i).replc, Wrap:=wdFindContinue, Replace:=wdReplaceAll
        next i

        If Not myStoryRange.NextStoryRange Is Nothing Then
            Set myStoryRange = myStoryRange.NextStoryRange
        End If

    Loop Until myStoryRange.NextStoryRange Is Nothing
Next MyStoryRange

I hope this helps somebody at some time
Spilly


text:
Q: When using unpacking(**) in Python can the dictionary your sending to the function include more variables than the function requires? I am learning how to unpack dictionaries with function in python and can't seem to get my code to work when my dictionary has a key/index that is not asked for the in the function. Is this something that just isn't possible? I am just trying to understand how unpacking works! Any help is much appreciated.
Check out my code below:
def customer_profiles(country, name):
    print("{},{}".format(name, country))

customer_profiles(**{"gender" : "male", "name" : "David" , "country" : "USA"})

This is the error message I get.
Traceback (most recent call last):
  File "luggage.py", line 12, in <module>
customer_profiles(**{"gender" : "male", "name" : "David" , "country" : "USA"})
TypeError: customer_profiles() got an unexpected keyword argument 'gender'

A: You can do this by providing a dummy variable for the rest of the keyword arguments to be put in:
def customer_profiles(country, name, **kwargs):
    print("{},{}".format(name, country))

customer_profiles(**{"gender" : "male", "name" : "David" , "country" : "USA"})

A: You can accept an arbitrary amount of keyword args, then only use the ones you need:
def customer_profiles(**kwargs):
    print("{},{}".format(kwargs["name"], kwargs["country"]))

customer_profiles(**{"gender" : "male", "name" : "David" , "country" : "USA"})

Output:
David,USA


text:
Q: В IE7 не работает JSON Имею такую ошибку:

SCRIPT5009: 'JSON' is undefined jquery.jsoncookie.js, line 50 character 3

В плагине jquery.jsoncookie.js 3 не находит 'JSON'.
SCRIPT5009: 'JSON' is undefined
jquery.jsoncookie.js, line 50 character 3

document.cookie = [
        key, "=", encode( JSON.stringify( value ) ),
        expires ? "; expires=" + expires.toUTCString() : "",
        options.path ? "; path=" + options.path : "",
        options.domain ? "; domain=" + options.domain : "",
        options.secure ? "; secure" : ""
    ].join( "" );

A: А вы реализацию JSON подключили (как написано здесь внизу)? У IE 7 нет нативного объекта JSON.


text:
Q: Amazon Beanstalk Spring Boot deployment I am deploying Spring Boot Application in Amazon BeanStalk.
Created a new RDS Postgres instance and connected to that instance using Postgres Client Application. Then created a new database in that. Then Changed database configuration to that instance in my local system Spring boot application. Then I able to connect to that database and use it through the application. But when deployed as a war file in Amazon Beanstalk. It is not working. Showing error as
Unable to obtain JDBC Connection
Any Solution?
Thanks in Adavance


text:
Q: Why do gases have weight? I know that a gas is made of atoms or molecules moving freely in space.
When these particles hit the walls of where they're kept in they cause something called pressure.
But these particles never pile up on each other and push a surface down by their weight so that we can measure it as weight, not pressure.
So why do gases have weight?

A: Imagine a gas molecule in a closed box bouncing vertically between the top and bottom of the box. Let's suppose the mass of the gas molecule is $m$ and its speed at the top of the box is $v_t$.
When the gas molecule moving upwards hits the top of the box and bounces back the change in momentum is $2mv_t$. If it does this $N$ times a second then the rate of change of momentum is $2Nmv_t$, and rate of change of momentum is just force, so the upwards force the molecule exerts is:
$$ F_\text{up} = 2Nmv_t $$
And the same argument tells us that if the velocity of the molecule at the bottom of the box is $v_b$, then the downwards force it exerts on the bottom of the box is:
$$ F_\text{down} = 2Nmv_b $$
So the net downwards force is:
$$ F_\text{net} = 2Nmv_b - 2Nmv_t = 2Nm(v_b - v_t) \tag{1} $$
But when the molecule leaves the top of the box and starts heading downwards it is accelerated by the gravitational force so when it reaches the bottom it has speeded up i.e. $v_b \gt v_t$. So that means our net downward force is going to be positive i.e. the molecule has a weight.
We can make this quantitative by using one of the SUVAT (see 'Physics For You' by Keith Johnson) equations:
$$ v = u + at $$
Which in this case gives us:
$$ v_b - v_t = gt $$
where $t$ is the time the molecule takes to get from the top of the box to the bottom. The number of times per second it makes this round trip is:
$$ N = \frac{1}{2t} $$
Substituting these into our equation (1) for the force we get:
$$ F_\text{net} = 2 \frac{1}{2t} m(gt) = mg $$
And $mg$ is of course just the weight of the molecule.

A: As stated in other answers, a gas, like all other matter has weight because it has mass. When you think about pressure, it's usually in the context of an example where the pressure exerted on the walls of a container is many, many times larger than the forces created due to weight.
Consider that our atmosphere at sea level has a pressure of about 101,325 Newtons per square meter and density of about 1.225 kg per cubic meter. That means a one meter cube of air will be pushing down on the ground with a force of 101,325 Newtons due to the motion of the gas molecules with about 12 Newtons (1.225 kg x 9.8 m/s/s) because of the weight of that quantity of gas. Although that 101,325 Newtons actually represents the weight of a one square meter column of air reaching all the way up into space.
Another way to look at it: we know that atmospheric pressure decreases with altitude. It might be more correct to say that atmospheric pressure increases with depth because of the weight of the air in the column above it. In the case of Earth, a column hundreds of miles high (although almost all of it is in the bottom 100 miles).

A: Think of the atmosphere as if it were an ocean. You might not think water has weight if you were diving underwater, but obviously when you fill up your cup with water you feel its weight increase. The atmosphere is really just a gaseous ocean on top of the surface. In extension, if you were to light a candle on the edge of a building taller than the Earth's atmosphere (assuming you had an oxygen source), you would see the smoke fall towards the Earth.

But these particles never pile up on each other and push a surface down by their weight so that we can measure it as weight, not pressure.

This is simply false. Gaseous particles do exert forces on surfaces. It's just that the scales we have are designed to subtract the cumulative forces of air particles. If you were to tare a scale in atmospheric pressure and then place it in vacuum, it would give a negative reading because the weight of gases are no longer present.

A: Here is a short answer: Imagine you would have an empty box (i.e. vacuum), that you would put on a weighing scale. It would have some weight. Now, if you would insert some gas into it, the measured weight would increase exactly by the mass of the gas times gravity.
Historically, this is quite an important point when they burned stuff (solid to gas) in a closed box on a weighing scale, and figured out that there was no measurable loss of weight.
On a microscopic scale, the explanation (see other answers for details, here's the short form) is simply that each molecule hits the bottom with greater speed than the top of the box, due to continuous acceleration towards the bottom. In fact, this has the side effect that the pressure at the top is slightly lower than the pressure at the bottom. Btw, this difference in pressure just equals the weight of the gas. This pressure difference becomes obvious if the box is very high, let's say ... the height of our atmosphere.
Lastly, the "reason" that molecules don't pile up is that collisions on a molecular level are quite different from collisions of let's say balls at macroscopic scale. At molecular level, there is no net energy loss due to friction or plastic deformation (assuming equal temperature). To phrase it a bit exaggerated: Collisions of molecules are perfectly elastic (not exactly true, but good enough for the point here), so they bounce forever.

A: Because they have mass.
And thus when in a gravitational field are accelerated towards other objects with mass, like the Earth.

A: Do correct me if I'm wrong.
1) The atoms in a solid have little kinetic energy (KE), the atoms in a gas have a lot of KE.
However, the net force exerted by a gas on a container and the net force exerted by a solid on a container is the same (in the absence of gravity), and in this case, zero, because the forces cancel out. If we were to put two containers, one containing a solid and one a gas (solid and gas has the same masses) in a uniform gravity field, the pressure difference between the top and bottom surfaces of each container is actually the same (Because the number of molecules in both containers are the same, and the average net force on each molecule is just the weight of the molecule. The gas molecules moving upwards will now move upwards at a lower velocity, those moving downwards will move downwards with a higher velocity). The only difference is that the pressure on the sides of the container containing the gas is higher than that containing the solid.
2)The atoms in a solid are fixed in position and hence always in contact with the weighing scale. The molecules in a gas are usually floating around and only in contact with the weighing scale for a short duration of time (when they collide).
As a result, a solid will apply a constant force on the weighing scale but a gas will only apply force when a molecule collides with the scale. We may wrongly assume that as a result, more force is being transmitted by the solid than the gas. However, if we were to average out the force applied by the solid or gas over time, we will find that they are in fact the same. This is because the gas molecule exerts much more force on the scale when it collides then an atom of a solid, for the same time period.
Edit: Also, the atoms in a solid do not accelerate. The moment they experience a gravitational force, they transmit it to the atoms below them. The molecules in a gas can accelerate, so they are likely to exert more force when they collide.


text:
Q: visual studio not responding on build I have a strange problem with VS2008.  My solution has 8 projects (all c#) and hangs VS when I build.  The task manager says "not responding" and the process takes 100% of one of my cores, and the memory usage gradually climbs.  Eventualy the IDE responds again, builds and deploys.  The hang time seems to grow longer and longer each time I build, but then when I reboot there is no hang and it goes right to the build.  Anyone know why?

A: You can run Visual Studio in a way as to log what is happening.
Open your IDE directory, find devenv.exe.config, and add this line:
  <system.diagnostics>
        <trace autoflush="true" indentsize="4">
            <listeners>
               <add name="myListener"
type="System.Diagnostics.TextWriterTraceListener, System version=1.0.3300.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\myListener.log" />
               <remove name="Default" />
            </listeners>
        </trace>
    </system.diagnostics>

This should create a log file on you c drive (once you restart visual studio).
Be sure to backup your existing devenv.exe.config first.
View the log and hopefully you will see which actions are causing it to take so long.

A: No idea, but what happens when you run MSBuild on the command line with your solution?  Does it hang?  If so, run it again with full verbosity and see where it hangs.

A: I had the same problem. It seems that my antivirus (avast) was detecting the compiled program as malware and blocking it. When I tried to build with avast's "File System Shield" turned off, I had no problem.
Try to turn "File System Shield" off, or even better disable the specific folder through "File System Shield" options.

A: By default Visual Studio build only uses 1 core!
To get the build process to use all cores use MSBuild!
Have a read of this excellent blog entry on Speeding Up Visual Studio Builds


text:
Q: Android onSaveInstance State not working (for me) I have an application that acts like a clapperboard, in which I use a variable i going to i++ every millisecond (I need milliseconds to display frames per second, and the chronometer updates only once per second), then I display it in the format HH:MM:SS:FF. I also have a quit button which goes by
if (item.getTitle() == "Quit") {
Process.killProcess(id);
}

The problem is that I want the app to remember the value of i when I press quit, so the timer would start at the same point it was before quitting it if I start it again.
I tried
public void onSaveInstanceState(Bundle outState) {
outState.putLong(MILLISECONDS, i);
super.onSaveInstanceState(outState);
}

then calling it by
public void onStart(Bundle savedInstanceState) {
super.onStart();
i = savedInstanceState.getLong(MILLISECONDS);
}

and
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
i = savedInstanceState.getLong(MILLISECONDS);
}

but it doesn't work.
Also if I go with
onCreate(Bundle savedInstanceState) {

...

i = savedInstanceState.getLong(MILLISECONDS);

...

}

the app force closes.
Any idea of what I'm doing wrong, please?
Thank you very much.

A: You are not really doing it the Android way :-) Don't kill your app, but go back to home. In that case, saveinstancestate will be called.

A: It would help if you added some more details to your question:
"It doesn't work" -> how exactly does it not work?  Is savedInstanceState empty?  Does it through an exception?
"the app force closes" -> can you provide the exact exception that is thrown, or the logcat text around the crash?
That being said, this section of documentation on saving persistant state might be helpful.  There are two different times to save state, in onPause and in onSavedInstanceState.  onPause is the more reliable one, because it is gauranteed to be called as part of the activity lifecycle.
If you save in onSaveInstanceState, you should recreate in onCreate.  However, as Sebi pointed out, the way you are killing the application might be preventing onSaveInstanceState from being called at all.
If you want to end your activity, just call finish().


text:
Q: C++ output not showing in PHP i have a small problem, i have a c++ program, but PHP is not showing output, only "blank". I made a small program to test, when I use "printf" and "gcc" to compile, it works fine, but when I compile the same progran using "g++" it fails to show the content in the php page. Any ideas? I can't use "gcc" because my project is in c++
I'm using this version of gcc/g++
g++ (GCC) 4.5.1 20100924 (Red Hat 4.5.1-4)
EDIT: I simplified the problem so you can understand what is going on here, thanks for your help. Now i get a missing library error.
I compiled the files using the followings commands:
gcc -o prueba1 prueba.c
g++ -o prueba2 prueba.cpp

So "prueba1" is the one compiled with GCC and "prueba2" is the one compiled with G++
Here is the file test.php
<?php
      echo "Executing file compiled with GCC
";
      echo shell_exec("./prueba1");
      echo "
";
      echo "Executing file compiled with G++
";
      echo shell_exec("./prueba2 2>&1");
?>

I get this on the browser:
Executing file compiled with GCC
Hello World (GCC)
Executing file compiled with G++
./prueba2: /opt/lampp/lib/libgcc_s.so.1: version `GCC_4.2.0' not found (required by /usr/lib/libstdc++.so.6)

Here is the prueba.c file:
#include <stdio.h>

int main(int argc, char *argsv[]){

printf("Hello World (GCC)\n");

return(0);

}

Here is the prueba.cpp file:
#include <iostream>

using namespace std;

int main(int argc, char *argsv[]){

cout << "Hello World (G++)" << endl;

return(0);

}

A: Rename the /opt/lampp/lib/libgcc_s.so.1 to /opt/lampp/lib/libgcc_s.so.1.backup, it seems C++ was trying to access this one instead the one that linux does when running from command line, thanks for the help guys


text:
Q: Подключение к БД Firebird от чужой роли. Добрый день, форумчане. Столкнулся с следующей проблемой. Мы используем БД Firebird 2.5, в которой куча ролей и пользователей. При подключении пользователя от чужой роли само подключения почему-то происходит, но при первом же запросе вылетает ошибка о недостаточности прав на таблицу или процедуру например.
Как я сам понимаю, подключение вообще не должно происходить, но почему-то это не так.
Как решить эту проблему?


text:
Q: How do i modify a field in a property How do i modify a field in a property that is a struct?
For example:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    struct vector
    {
        public vector(int theX, int theY)
        {
            x = theX;
            y = theY;
        }
        public int x;
        public int y;
    }

    class SomeClass
    {
        public vector myVector { get; set; }
        public SomeClass()
        {
            myVector = new vector(10, 20);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SomeClass me = new SomeClass();
            me.myVector.x = 200; //Error

            Console.Read();
        }
    }
}

If the vector was a class, then i would be able to modify it.
So my question is: How can i modify it if it was a struct?
So far, my solution would be setting my current vector to a new vector
for example (if i only wanted to modify the x value):
me.myVector = new vector(200,me.myVector.y);

A: Structs are supposed to be immutable. You shouldn't be able to modify a property in your struct. The correct way to modify myVector would be to assign a new instance to the property.
If you want to create a more convenient API, I suggest you design your struct like this:
public struct vector
{
    private readonly int x;
    private readonly int y;

    public vector(int theX, int theY)
    {
        x = theX;
        y = theY;
    }

    public int X { get { return this.x; } }
    public int Y { get { return this.y; } }

    public vector SetX(int x)
    {
        return new vector(x, this.y);
    }

    public vector SetY(int y)
    {
        return new vector(this.x, y);
    }
    .. other operations
}

me.myVector = me.myVector.SetX(200);

A: While what has been said before is true - you should make your structs immutable - they aren't that way by default.  You CAN mutate a struct in the setup that you have.
I originally said that you needed to initialize your struct, which was then noted that it was.  So I went back and re-evaluated the problem, and realized I wasn't thinking right.
The issue is the semantics of a value type.  When you do
me.myVector

you're getting a copy of the value of the struct, not a reference to it.  Then subsequently trying to modify a value on that struct in the same line doesn't make sense.
This below code may make it a bit clearer:
static void Main(string[] args)
{
    SomeClass me = new SomeClass();
    //me.myVector.x = 200; //Error

    // Get a local copy of the struct, which is NOT a reference to the me.myVector variable.
    vector myVec = me.myVector;
    // Now mutate the value of the local struct
    myVec.x = 3;
    int xNew = myVec.x; // xNew = 3

    int xOld = me.myVector.x; // xOld still = 10

    Console.Read();
}

So, following on to this, here is how you can make a mutable value type, in which your code would work (note that the myVector property must be a directly accessible field, or be a property with a backing field which you access in the MutateStruct call):
class SomeClass
{
    public vector myVector;
    public SomeClass()
    {
        myVector = new vector(10, 20);
    }

    public void MutateStruct(int newX)
    {
        myVector.x = newX;
    }
}

class Program
{
    static void Main(string[] args)
    {
        SomeClass me = new SomeClass();

        me.MutateStruct(200);
        int newerX = me.myVector.x; // newerX is now 200

        Console.Read();
    }
}

A: Structs should generally represent one of two things:

*

*A single unified entity, such as a fractional number or a moment in time (e.g. a Decimal or Date).

*A small fixed collection of independent variables stuck together with duct tape, which may sometimes be used individually and sometimes as a group (e.g. the coordinates of a 3d point), and which have no identity beyond the values they contain (so that e.g. any Point3d with values [1,4,7] is equivalent to any other with those same values).
Microsoft's guidelines are good when applied to things of the first type, but whoever wrote them failed to consider that some useful concepts fit the second pattern much more so than the first.  By the sound of things, your data type fits that second pattern.  As such, it should have its entire state exposed as public fields (which you do).  Further, it should in many cases, when practical, be passed as a ref parameter.  If an exposed-field class is passed as a ref parameter, the recipient will be able to modify its fields about as easily as it could modify single variables of the corresponding types.  Unfortunately, there is no mechanism for exposing properties as ref parameters.  Unless you write your own methods which pass structures as ref parameters and use those instead of properties, your best bet will probably be to do something like:
var temp = something.myVector;
temp.X += 200;
something.myVector = temp;

an alternative (which could be advantageous if myVector had many fields) would be to have a method in someThing like:
delegate void ActByRef<T1>(ref T1 p1);
delegate void ActByRef<T1>(ref T1 p1, ref T2 p2);

void modifyMyVector(ActByRef<myVector> actor)
{
  actor(ref _myVector); // _myVector must be manual prop with backing field
}
void modifyMyVector<TX1>(ActByRef<myVector, TX1> actor, ref TX1 px1)
{
  actor(ref _myVector, ref px1);
}

A caller that wanted to e.g. add 4 to X of myVector could write
something.ModifyMyVector((ref myVector vec) => vec.X+=4;)

If the caller had a vector called velocity and it wanted to add a vector perpendicular to that to something.myVector it could do:
something.ModifyMyVector((ref myVector vec, ref myVector vel) =>
  { vec.X += vel.Y; vec.Y -= vel.X; }, ref velocity);

Note that using ref parameters with open-field structures can be very efficient, since the time required to pass a struct by ref is independent of its size.  Unfortunately, none of the Framework collections have any such facilities built in, and C# doesn't do much to make such code convenient.  Even the approach using the temp variable is apt to be cleaner and more efficient, however, than code using so-called "immutable" structures or immutable classes.


text:
Q: Get the direction arrow toward the SCNNode once that node is not visible in ARCamera If ARCamera moving left, right, up or down and if that node becomes invisible in ARCamera. I want to indicate the arrow that you need to move camera up/down/right/left.

A:     if let pointOfView = sceneView.pointOfView{
        let isMaybeVisible = sceneView.isNode((displayNode.presentation), insideFrustumOf: pointOfView)
        if isMaybeVisible{
            if arrowVisible{
                 arrow.removeFromParentNode()
            }
        }else{
            if !arrowVisible{
                 sceneView.pointOfView?.addChildNode(arrow)
            }
        }
    }

isNode(_:insideFrustumOf:) here checks if node is visible in ARCamera.
 Use it inside renderer(_:updateAtTime:)
Edit:
Arrow here is a node (3d arrow). Remember the point of arrow need to face -z axis
    let scene = SCNScene(named: "art.scnassets/arrow.dae")
    let arrow = scene?.rootNode.childNode(withName: "arrow", recursively: false)
    arrow.constraints = [SCNLookAtConstraint.init(target: node)]


text:
Q: TensorFlow String Input Producer Size()

Trying to do a sanity check on the size of the queue created by tf.train.string_input_producer (r1.3) but just get zero size when expected to get size of three
import tensorflow as tf

file_queue = tf.train.string_input_producer(['file1.csv','file2.csv','file3.csv'])

print('type(file_queue): {}'.format(type(file_queue)))

with tf.Session() as sess:

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    file_queue_size = sess.run(file_queue.size())

    coord.request_stop()
    coord.join(threads)

print('result of queue size operation: {}'.format(file_queue_size))

My hunch was that there was some sort of lazy initialization going on so I figured I would ask the queue for an item and see what the size was after
import tensorflow as tf

file_queue = tf.train.string_input_producer(['file1.csv','file2.csv','file3.csv'])

print('type(file_queue): {}'.format(type(file_queue)))

with tf.Session() as sess:

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    item = sess.run(file_queue.dequeue())
    file_queue_size = sess.run(file_queue.size())

    coord.request_stop()
    coord.join(threads)

print('result of queue size operation: {}'.format(file_queue_size))

While the size is no longer zero, the size provided is not two and changes every time the code is run.
I feel like getting the size is a simple thing but maybe this is just not the way to interact with data_flow_ops.FIFOQueue.  Any insight to explain what is going on here would be much appreciated.

A: This is an artifact of the async nature in which queues are filled up by the queue runners. Try this code:
import tensorflow as tf
import time

file_queue = tf.train.string_input_producer(['file1.csv','file2.csv','file3.csv'])

print('type(file_queue): {}'.format(type(file_queue)))

with tf.Session() as sess:

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    time.sleep(1)
    file_queue_size = sess.run(file_queue.size())

    coord.request_stop()
    coord.join(threads)

print('result of queue size operation: {}'.format(file_queue_size))

The output should say result of queue size operation: 32. By pausing the main thread, the queue runners could run for long enough to fill up the queue.
Why 32 and not 3? Let's look at the signature for string_input_producer:
string_input_producer(
    string_tensor,
    num_epochs=None,
    shuffle=True,
    seed=None,
    capacity=32,
    shared_name=None,
    name=None,
    cancel_op=None
)

Two main things to note here:

*

*num_epochs=None means keep iterating on the list of items forever. To iterate over the list just once set num_epochs=1. You will also need to call sess.run(tf.local_variables_initializer()). With num_epochs=1 if you run the size op after dequeues you will see the size reducing.

*capacity=32 this is the default capacity of the queue. Which is why we are seeing 32 instead of 3 in the output above.


text:
Q: Python:ValueError: scatter requires y column to be numeric? Using pd.Dataframe won't convert columns of lists into dataframe :
Below are my lines of code for reading in a .mat file and converting it into a dataframe from the many examples that I have seen.
However, when I read the data in the columns they still remain as lists with square brackets around the data. What I am trying to do is convert this into a proper dataframe so I can plot the last column (time data) along with the other columns as an x and y scatter plot. But the error I get is ValueError: scatter requires y column to be numeric. I have not shown the code for plotting the x and y  data.
import mat4py as mp
data = mp.loadmat('test.mat')
df = pd.DataFrame(data)

When I type:
df.columns

I get the following:
Index(['col 1', 'col 2',
       'col 3', 'col 4', ... 'col 189'] with dtype='object', length=189)

If I type:
df.['col 1']

I get the following:
Out[95]:
0       [0.0]
1       [0.0]
2       [0.0]
3       [0.0]
4       [0.0]
5       [0.0]
6       [0.0]
7       [0.0]
8       [0.0]
9       [0.0]
... 1622 rows in total.

I even tried using .apply(pd.to_numeric, errors='coerce') to the columns and that does not work either. What am I doing wrong?
Update:
The solution in the comments presented below applied only for a single column, but I wanted this to apply to every cell in the dataframe. When using .apply(lambda ..) on a whole dataframe, the columns become the index and messes up the dataframe. I found the solution that would properly apply the lambda to each cell and retain the dataframe. It is as follows:
mm = df.applymap(lambda x: x[0])

Many thanks to those who provided the original lambda solution.

A: You can do
df=pd.DataFrame({'col 1':[[0.0],[0.0]]})
df
Out[49]:
   col 1
0  [0.0]
1  [0.0]
df['col 1'].apply(lambda x : x[0])
Out[50]:
0    0.0
1    0.0
Name: col 1, dtype: float64

A: If [0.0] are strings,
import ast
df.c.transform(ast.literal_eval).str[0]
1    0.0
2    0.0
3    0.0
4    0.0
5    0.0
6    0.0
7    0.0
8    0.0
9    0.0


text:
Q: Opening itms-service from Flutter I use the enterprise distribution from Apple for our app. Now I'm creating a simple update system which starts the installation of a new app version.
Therefore I need to call:
var _url ="itms-services://?action=download-manifest&url=https://my-url-to-the-plist"
I have done the same in other frameworks (Adobe AIR) with no problem.
In Flutter I use the url_launcher package with no success. The Urls scheme seems not to be supported by Flutter?
Any Ideas to this?


text:
Q: CSS - Grid/Masonry Layout I have created a grid layout like so (JSFIDDLE):
HTML:

CSS:
.grid-box > .item-9 > .box-1 {
    background: none repeat scroll 0 0 #990066;
    display: inline-block;
    float: left;
    height: 200px;
    width: 49%;
}
.grid-box > .item-9 > .box-2 {
    background: none repeat scroll 0 0 #3333FF;
    display: inline-block;
    float: right;
    height: 400px;
    width: 26%;
}
.grid-box > .item-9 > .box-3 {
    background: none repeat scroll 0 0 #993366;
    display: inline-block;
    float: right;
    height: 100px;
    width: 25%;
}
.grid-box > .item-9 > .box-4 {
    background: none repeat scroll 0 0 #FF66FF;
    display: inline-block;
    float: right;
    height: 100px;
    width: 25%;
}
.grid-box > .item-9 > .box-5 {
    background: none repeat scroll 0 0 #CC66CC;
    display: inline-block;
    float: left;
    height: 140px;
    width: 24.5%;
}
.grid-box > .item-9 > .box-6 {
    background: none repeat scroll 0 0 #9966CC;
    display: inline-block;
    float: left;
    height: 140px;
    width: 24.5%;
}
.grid-box > .item-9 > .box-7 {
    background: none repeat scroll 0 0 #CC6699;
    display: inline-block;
    float: right;
    height: 100px;
    width: 25%;
}
.grid-box > .item-9 > .box-8 {
    background: none repeat scroll 0 0 #9966CC;
    display: inline-block;
    float: right;
    height: 100px;
    width: 25%;
}
.grid-box > .item-9 > .box-9 {
    background: none repeat scroll 0 0 #990066;
    display: inline-block;
    float: left;
    height: 60px;
    width: 49%;
}

And then I ran into a slight issue, I need box-2 left aligned to block-1 so basically i need to switch the positions of the big blue block with the 4 multicolored blocks. I have placed '>' and '<' arrows to illustrate what i mean.
Also I cant edit the HTML, as it is generated by PHP.. I can only edit the CSS. Also I cant Edit the sizes, such as width an Height.
Any Help Greatly Appreciated.

A: You can push the elements left and right with
position: relative
left/right: XX%

http://jsfiddle.net/HerrSerker/ukEfY/6/
/* ... */
.grid-box > .item-9 > .box-2 {
    /* ... */
    position: relative;
    left: -25%;
}
.grid-box > .item-9 > .box-3 {
    /* ... */
    position: relative;
    left: 26%;
}
.grid-box > .item-9 > .box-4 {
    /* ... */
    position: relative;
    left: 26%;
}

/* ... */

.grid-box > .item-9 > .box-7 {
    /* ... */    position: relative;
    left: 26%;
}
.grid-box > .item-9 > .box-8 {
    /* ... */
    position: relative;
    left: 26%;
}
/* ... */

A: using absolute positioning, it can be done like that Working Fiddle
Notice: it's a very strict layout. (every position is fixed)
As you requested, the changes are only in the CSS.
HTML:

1

2

3

4

5

6

7

8

9

CSS:
.grid-box > .item-9
{
    position: relative;
}
.grid-box > .item-9 > [class *= 'box-']
{
    position: absolute;
}
.grid-box > .item-9 > .box-1 {
    background: none repeat scroll 0 0 #990066;
    height: 200px;
    width: 50%;
}
.grid-box > .item-9 > .box-2 {
    background: none repeat scroll 0 0 #3333FF;
    height: 400px;
    width: 25%;
    left: 50%;
}
.grid-box > .item-9 > .box-3 {
    background: none repeat scroll 0 0 #993366;
    height: 100px;
    width: 25%;
    right: 0;
}
.grid-box > .item-9 > .box-4 {
    background: none repeat scroll 0 0 #FF66FF;
    height: 100px;
    width: 25%;
    right: 0;
    top: 100px;
}
.grid-box > .item-9 > .box-5 {
    background: none repeat scroll 0 0 #CC66CC;
    display: inline-block;
    height: 140px;
    width: 25%;
    top: 200px;
}
.grid-box > .item-9 > .box-6 {
    background: none repeat scroll 0 0 #9966CC;
    height: 140px;
    width: 25%;
    top: 200px;
    left: 25%;
}
.grid-box > .item-9 > .box-7 {
    background: none repeat scroll 0 0 #CC6699;
    height: 100px;
    width: 25%;
    top: 200px;
    right: 0;
}
.grid-box > .item-9 > .box-8 {
    background: none repeat scroll 0 0 #9966CC;
    height: 100px;
    width: 25%;
    top: 300px;
    right: 0;
}
.grid-box > .item-9 > .box-9 {
    background: none repeat scroll 0 0 #990066;
    top: 340px;
    height: 60px;
    width: 50%;
}


text:
Q: Are different screens used for the Toshiba Chromebook CB30-102? Recently my screen broke on my Toshiba Chromebook CB30-102. I then ordered a new screen online. In the listing, it said the screen was for a "Toshiba Chromebook CB30-102" so I imaged this was all good. However, after it arrived it turned out to be a 30 pin screen. My machine, however, required a 40 pin screen with hooks at a different position. After contacting the seller I was told that the CB30-102 uses either of two very different screens and I simply ordered the wrong screen.
I have tried to look this up online but the official Toshiba site does not list details of the screen of this machine. How can I find out which screen(s) fit this particular laptop model?

A: Usually you note down all the codes you can find on your device as they are, then contact Toshiba support, tell them that you broke the screen of your device, provide them all the details and ask them for the spare part number of the screen. They should be able to figure it out, if necessary they ask you for more details. At worst they will tell you what the spare part number is and that it is out of stock. That's what my experience is with other manufacturers, technical support and 3rd party technicians. There should be a versioning scheme that can be used to identify which components have been used in a particular device, else everyone else would be as puzzled as you are now.
It's awkward to see that you just provided an almost ambigous model number,
then they did what looked like their best effort to them while apparently already knowing that there is more than one part with completely different specifications and decided "okay, we will ship this part! thank you for business!". Not nice nor trustworthy at all.


text:
Q: Convert time to character in R I read a dataframe dtmn from a csv file with the following time value.
In Excel it shows:
7/4/2014 13:08
When I read it in R it shows:
> x <- dtmn[2,1]
> x
[1] 7/4/2014
Levels: 0.547222222 7/4/2014 7/4/2014 13:08 788

I would like to convert this into a character form, with the following character values:
"07/04/2014 13:08"

The function as.character.Posixt(dtmn[2,1]) returns date only : [1] "7/4/2014"
But I am trying to include the time also. So the desired output may look like this:
"07/04/2014 13:08"
Please help,

A: An easy way to solve this is using the readxl package. Suppose you have an excel file named excel_file.xlsx, and your data column is formatted as date in Excel:
date_from_excel
07/04/14 13:08
07/04/14 21:30
07/12/14 10:18

library(readxl)

df = read_excel(path=paste0("/<path-to-the-file>/",'excel_file.xlsx'), sheet=1, col_names=T, col_types=c('date') )
df = as.data.frame(df)
df$date_as_string = as.character(df$date_from_excel)

> df
  date_from_excel      date_as_string
1 2014-04-07 13:08:00 2014-04-07 13:08:00
2 2014-04-07 21:30:00 2014-04-07 21:30:00
3 2014-12-07 10:18:00 2014-12-07 10:18:00

> str(df)
'data.frame':   3 obs. of  2 variables:
 $ date_from_excel: POSIXct, format: "2014-04-07 13:08:00" "2014-04-07 21:30:00" ...
 $ date_as_string : chr  "2014-04-07 13:08:00" "2014-04-07 21:30:00" "2014-12-07 10:18:00"

A: Rich Scriven's comment helped me understand this. I checked the class and levels.
> class(dtmn[2,1])
[1] "factor"
> levels(dtmn[2,1])
[1] "0.547222222"    "7/4/2014"       "7/4/2014 13:08" "788"

Finally, calling the third level as character:
> as.character(levels(dtmn[2,1])[3])
[1] "7/4/2014 13:08"


text:
Q: Python Generator Yield Dictionary I have a function that produces a large amount of data and store them in a dictionary that is to be returned at the end of the function. However I've been told that it's not efficient in terms of memory and that I should use data generator in Python.
Example:
def gen_data(dataz):
    data_dict = {"uniqz":[], "random":[]}

    for v in dataz:
        if dataz[v]["row"] == "ay1":
            data_dict["uniqz"].append(dataz[v]["row"])
        else:
            data_dict["random"].append(dataz[v]["val"])

    return data_dict

dataz = {"ax1":{"row":"ay1","val":2},
                "ax2":{"row":"ay2","val":3}}

print(gen_data(dataz))

How do I convert this block of code and make use of data generator/yield?
I know how to yield individual dictionary data, example:
for i in xrange(num_people):
        datadict = {
                    'id': i
                }
        yield datadict

But in the above scenario it should append all necessary data into the dictionary first before yielding. How do I do this?

A: It depends on how you want to use the data, from your code above you are creating all the values and processing it at once. generator are useful when you want to process data one at a time (or one batch at a time)
Here you can modify your code like this
def gen_data(dataz):
    for v in dataz:
        if dataz[v]["row"] == "ay1":
            yield ("uniqz", dataz[v]["row"])

        else:
            yield ("random", dataz[v]["val"])

then you can process your data like below
for key, value in gen_data(dataz):
    process(key, value)

In this way you will save the memory occupied by the dictionary. This will also be efficient in case of parallel processing. e.g. there will be some latency in getting new data and also in processing it, using generator, while you are getting data from some source it can be processed in parallel in different thread or machine


text:
Q: Not able to see Material-Ui Icon I am trying to add an icons using Material-UI but facing this error -
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (bundle.js:60941:17)
    at useContext (bundle.js:60949:24)
    at bundle.js:57580:66
    at renderWithHooks (bundle.js:33800:22)
    at updateForwardRef (bundle.js:35822:24)
    at beginWork (bundle.js:37810:20)
    at HTMLUnknownElement.callCallback (bundle.js:22750:18)
    at Object.invokeGuardedCallbackDev (bundle.js:22799:20)
    at invokeGuardedCallback (bundle.js:22859:35)
    at beginWork$1 (bundle.js:42601:11)
react-dom.development.js:20085 The above error occurred in the <MuiSvgIconRoot> component:

    at http://localhost:3000/static/js/bundle.js:57580:66
    at SvgIcon (http://localhost:3000/static/js/bundle.js:1493:82)
    at ExpandMoreIcon
    at div
    at div
    at sidebar
    at div
    at App
    at Provider (http://localhost:3000/static/js/bundle.js:45202:20)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
bootstrap:27 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (bundle.js:60941:17)
    at useContext (bundle.js:60949:24)
    at bundle.js:57580:66
    at renderWithHooks (bundle.js:33800:22)
    at updateForwardRef (bundle.js:35822:24)
    at beginWork (bundle.js:37810:20)
    at HTMLUnknownElement.callCallback (bundle.js:22750:18)
    at Object.invokeGuardedCallbackDev (bundle.js:22799:20)
    at invokeGuardedCallback (bundle.js:22859:35)
    at beginWork$1 (bundle.js:42601:11)

This is my code
I have also added a test and it is returning true in the console but still unable to see the icon on my screen
A blank page is being returned


text:
Q: Rotational kinetic energy in double pendulum Why is the rotational kinetic energy term for the point mass of kinetic energy for a double pendulum not included in the Lagrangian equation?
\begin{align}
T&=\frac{m_1+m_2}2\ell_1^2\dot\theta_1^2+\frac{m_2}2\ell_2^2\dot{\theta}_2^2+m_2\ell_1\ell_2\dot{\theta_1}\dot{\theta}_2\cos\left(\theta_1-\theta_2\right),\\
U&=-\left(m_1+m_2\right)\ell_1g\cos\theta_1-m_2\ell_2g\cos\theta_2
\end{align}

A: It is there, it's just hidden by the change of coordinates. Written in Cartesian coordinates, the kinetic energy is
$$
T=\frac12m_1\dot{x}_1^2+\frac12m_1\dot{y}_1^2+\frac12m_2\dot{x}_2^2+\frac12m_2\dot{y}_2^2+\frac12I_1\dot\theta_1^2+\frac12I_2\dot\theta_2^2\tag{1}
$$
where the last term is the rotational kinetic enregy.
If you let
\begin{align}
x_1&=\frac12\ell_1\sin\theta_1\\
y_1&=-\frac12\ell_1\cos\theta_1\\
x_2&=\ell_2\left(\sin\theta_1+\frac12\sin\theta_2\right)\\
y_2&=-\ell_2\left(\cos\theta_1+\frac12\cos\theta_2\right),
\end{align}
then take the appropriate derivatives, you'll find that $T$ defined in (1) is equivalent to the $T$ defined in your problem.


text:
Q: Javascript convert array of objects to tree I am trying to convert this structure:
var initial = [
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];

to this one:
var example = {
"Phase 1": {
    "Step 1": {
        "Task 1": { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
        "Task 2": { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }
    } ,
    "Step 2": {
        "Task 1": { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
        "Task 2": { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }
    }
} ,
"Phase 2": {
    "Step 1": {
        "Task 1": { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
        "Task 2": { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    } ,
    "Step 2": {
        "Task 1": { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
        "Task 2": { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
    }
}
};

so I can easily extract a value like this example['Phase 2']['Step 1']['Task 1']['Value']
I have done the first step using a groupBy function like this one:
function groupBy(d, arr) {
return arr.reduce(function(acc, i) {
    var p = i[d];
    var temp = acc[p] || [];
    temp.push(i);
    acc[p] = temp;
    return acc;
}, {})
}

so when I do var groupedByPhase = groupBy('Phase', initial);
I get for groupedByPhase:
{
"Phase 1" : [
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
],
"Phase 2": [
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]
}

I also manage to group by Step using this function:
function groupByInNestedObj(item, obj) {
var x = {};
for (var i in obj) {
    x[i] = groupBy(item, obj[i]);
}
return x;
}

which enables to get when calling groupByInNestedObj('Step', groupBy('Phase', initial))
 {
"Phase 1" : {
    "Step 1": [
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }],
    "Step 2": [
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    ]},
"Phase 2": {
    "Step 1:" [
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }],
    "Step 2:"[
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
    ]}
}

However I am a bit stuck here, to do the next one.
Ideally I would like to be able to do groupBy("Task", groupBy("Step", groupBy("Phase", initial))) so that groupBy groups at the deepest level of the tree.
Any suggestion welcome!
Note: I did try for the 2nd step to implement this function
function groupByInNestedObj2 (item, obj) {
    var x = {};
    for(var i in obj) {
        for (var j in obj[i]) {
            x[i][j] = groupBy(item, obj[i][j]);
        }
    }
    return x;
}

but it doesn't seem to work.
Note 2: The second version of the previous function works but is not pure as it modifies the object passed through it
function groupByInNestedObj2 (item, obj) {
    var x = {};
    for(var i in obj) {
        x[i] = obj[i]
        for (var j in x[i]) {
            x[i][j] = groupBy('Task', x[i][j]);
        }
    }
    return x;
}

so when I do var groupByPhaseAndStepAndTask = groupByInNestedObj2('Task', groupByPhaseAndStep) groupByPhaseAndStep is modified too, which is an undesirable side effect. Still working on it.

A: You can try use .reduce and just check if object exists or not, like this

var initial = [
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];

var result = initial.reduce(function (prev, current) {
  prev[current.Phase] = prev[current.Phase] || {};
  prev[current.Phase][current.Step] = prev[current.Phase][current.Step] || {};
  prev[current.Phase][current.Step][current.Task] = current;
  return prev;
}, {});

console.log(JSON.stringify(result, null, 2));

A: We can do it this with a single for loop:

var initial = [
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];
var final = {}
initial.forEach(function(d){
  if (!final[d.Phase]) //phase not present so make an object
   final[d.Phase] = {};
  if (!final[d.Phase][d.Step]) //step not present so make an object
   final[d.Phase][d.Step] = {};
  if (!final[d.Phase][d.Step][d.Task])//task not present so make an object and store the object
   final[d.Phase][d.Step][d.Task] = d;

})
console.log(final)

A: A more generic way using lodash and this answer:

var initial = [
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];

_.mixin({
  groupByMulti: function(obj, values, context) {
    if (!values.length) return obj;
    var byFirst = _.groupBy(obj, _.head(values), context);
    for (var prop in byFirst) {
      byFirst[prop] = _.groupByMulti(byFirst[prop], _.tail(values), context);
    }
    return byFirst;
  }
});

var tree = _(initial).groupByMulti(['Phase', 'Step', 'Task']);
$('#pre').append(JSON.stringify(tree, null, 3));


text:
Q: Javascript Array Performance I have checked each and every question and article about this, that I could find, but nothing really answers it. I make it sound as if I have just one question, there's more of them.
Maybe I should first explain what I am trying to do, I am building a File Manager entirely in JavaScript, the File Manager receives files from Backend (PHP, Twig), it then stores them in an array of Folder, each Folder has its own Files, Folders is an Array, and Files in each Folder is an Array as well, these Files are also shown on the page, and the user can select, copy, cut, paste ( other operations ) them ( I am still writing these operations, because here lies the problem ). Files on page have data-id assigned to them, so that I can easily operate on them between File Manager and the Backend, and because I know the ID of every and each file, I think I could completely eliminate traversing through Arrays of Files in search of a particular File, if I could only create an Array that would take the ID of a File as an Index, and because this is JavaScript, I can do that! but there are some problems with it.
Trying to use an Object for this task just does not work, because it is just way slower than Array ( now, I understand, that the differences in speed, even if in millions, are not that big, but why not try to dig for ultimate performance, right ? )
So here is a list of questions, that I cannot seem to find a reliable answer to:

*

*Why is Object on Chrome so much faster, than Object on Firefox ?

*Why is accessing an undefined index on Chrome so much slower ?

*Why is Array so much faster on Firefox, than on Chrome ?

*I know why Chrome loses performance with higher indexes ( at 100k it transforms the array into a list, I think, it was answered with a link to source in another question on SO ), but Firefox loses performance gradually as if it traveresed to higher indexes sequentially, even if accessed directly, why is that ?

*Why is an Array extermely slow when there is only one element in it, but that element is at a very high index ?

There are probably some more questions I have, but I cannot think of them right now.

The fastest configuration I found, that supports IDs as indexes and holes between them, as well as starting at a high index, is using an Array that holds the data you want to store, and another array, that just holds the indexes, so that when you are searching for an object with ID 10, you touch the index Array, instead of the Array with data.
You can see an example of this in http://jsperf.com/array-management-performance/2.
EDIT:
If you want to see the performance degradation, please "review" this jsperf and change minId and maxId to some big numebers.

Here are some stats:
Object
Read Defined: Firefox 165.173 mln ops/sec | Chrome 351.699 mln ops/sec
Read Undefined: Firefox 98.582 mln ops/sec | Chrome 54.666 mln ops/sec
Write Close: Firefox 7.599 mln ops/sec | Chrome 291.244 mln ops/sec
Write Far: Firefox 5.599 mln ops/sec | Chrome 93.733 mln ops/sec
Write Overwrite: Firefox 7.599 mln ops/sec | Chrome 291.244 mln ops/sec
Array
Read Defined: Firefox 681.206 mln ops/sec | Chrome 401.522 mln ops/sec
Read Undefined: Firefox 681.206 mln ops/sec | Chrome 62.827 mln ops/sec
Write Close: Firefox 400.234 mln ops/sec | Chrome 121.519 mln ops/sec
Write Far: Firefox 348.560 mln ops/sec | Chrome 121.519 mln ops/sec
Write Overwrite: Firefox 400.234 mln ops/sec | Chrome 234.337 mln ops/sec
P.S. Did you know, that Read Defined is faster on Chrome on Mobile, than on Chrome on Desktop ?
I jsperf-ed every single question I have here, so either my/others' tests were incorrectly written, or this is some really funky stuff.
http://jsperf.com/array-management-performance/2
http://jsperf.com/array-in-the-middle-of-nowhere
http://jsperf.com/object-holey-performance-better
http://jsperf.com/object-performance-better
http://jsperf.com/array-vs-object-mine-v2/5
P.S.2 I know, that one of the Array tests is actually testing Object, and another Object test is actually testing Array, please do not point that out, I am aware, I wrote this, the error is because jsperf is very poorly made, and I was trying to relatively quickly check a lot of different settings.
P.S.3 I am sorry, that some of these tests are really messy, I did not think, I would actually need to show them to anyone, but I still think there are sufficient.
---------------------------------------------------------------------------
EDIT: ( Answer, hopefully to re-open the question, so that I can answer it )
Here I go with an answer to all of our (my) problems. Now that I read my questions again, while having the answer, I can see how my questions could not be answered easily, or at all really, without digging into the sources of each browser.
I myself still do not know the exact answers to 1, 2, 3, 4 or even 5, but the answer that is correct, is "Because of implementation differences", it is as simple as that, obviously, I have not returned here to write just that, I have a solution to the problem I am showing in this question.
Simplified Problem:
You have a set of IDs, that are assigned to data, most likely from the DB.
You want that data in an array in JS, so that You can work with it very easily, but You DO NOT WANT to lose performance, while putting 100k elements into a JS array. How does one put N elements into an array in JS without losing read/write performance ? (I did not test write, because it is not that important to me).
Solution and Explanation:
While studying this problem, I have checked a mutlitude of potential solutions, like splines, fourier transformations, hash tables, binary search, and a twist on map/hash tables, that actually performed VERY well, but not well enough for my taste ( it would also perform worse with the increase in size ).
The final solution seems dead simple and obvious, but somehow ( I guess I'm dumb ) it took me 10 days to figure out, it scales perfectly, and access to any element is extremely fast O(1).
To be able to write this solution, I use this property of JS engines http://jsperf.com/array-of-arrays-with-high-indexes/2 , it would seem, that access to first 1000 elements IS SUPER FAST ( even in arrays of arrays ), and because I know my data is unsigned integers, I can easily map the integers from 1D to 3D, so that FastArray can hold up to a Billion elements.
You can see this solution in action right here: http://jsperf.com/map-check-v2/5 -- The first test is slow, because I read the sample data from a simple array, and that is very slow ... EDIT: This does not seem to be the case, I really do not know what is causing it, I think jsperf is kind of freaking out, because running just that test yields pretty good results, very weird.
A cleaner implementation is here https://github.com/ImJustAskingDude/JavascriptFastArray with a lot of references to the every page I read, to try to figure this out.
P.S.4 Moderators. please re-open this question, so that people searching for Ultimate Array Performance can see this answer in a nice actual Answer.
Thanks.
P.S.5 I do not know why, I guess there is a bug in my final code, that makes Chrome perform relatively poorly, which is probably easily fixable.

A: First of all, JS engines are different on every browser, so they don't perform equally on every case.
Also, you have to take in mind that arrays in JavaScript are Objects too, the only difference is that they have integers as their key values to simulate the indexes.
When you create an array with just one element at a high index the Object will be created with all the other "spaces" filled with undefined values so the JS engine have to traverse the whole structure to find your value.
As @RobG says, the native array methods like reduce, map, and forEach will perform a lot better in this case.
Also you can use functional libraries like Ramda or Lodash to help you traverse and flatten your queries results.


text:
Q: Cancelling a long running regex match? Say I'm running a service where users can submit a regex to search through lots of data. If the user submits a regex that is very slow (ie. takes minutes for Matcher.find() to return), I want a way to cancel that match. The only way I can think of doing this is to have another thread monitor how long a match is taking and use Thread.stop() to cancel it if necessary.
Member variables:
long REGEX_TIMEOUT = 30000L;
Object lock = new Object();
boolean finished = false;
Thread matcherThread;

Matcher thread:
try {
    matcherThread = Thread.currentThread();

    // imagine code to start monitor thread is here

    try {
        matched = matcher.find();
    } finally {
        synchronized (lock) {
            finished = true;
            lock.notifyAll();
        }
    }
} catch (ThreadDeath td) {
    // send angry message to client
    // handle error without rethrowing td
}

Monitor thread:
synchronized (lock) {
    while (! finished) {
        try {
            lock.wait(REGEX_TIMEOUT);

            if (! finished) {
                matcherThread.stop();
            }
        } catch (InterruptedException ex) {
            // ignore, top level method in dedicated thread, etc..
        }
    }
}

I've read java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html and I think this usage is safe since I'm controlling where ThreadDeath is thrown via synchronisation and handle it and the only damaged objects could be my Pattern and Matcher instances which will be discarded anyway. I think this breaks Thread.stop() because I'm not rethrowing the error, but I don't really want the thread to die, just abort the find() method.
I've managed to avoid using these deprecated API components so far, but Matcher.find() does not seem to be interruptible and can take a very long time to return. Is there any better way to do this?

A: With a little variation it is possible to avoid using additional threads for this:
public class RegularExpressionUtils {

    // demonstrates behavior for regular expression running into catastrophic backtracking for given input
    public static void main(String[] args) {
        Matcher matcher = createMatcherWithTimeout(
                "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "(x+x+)+y", 2000);
        System.out.println(matcher.matches());
    }

    public static Matcher createMatcherWithTimeout(String stringToMatch, String regularExpression, int timeoutMillis) {
        Pattern pattern = Pattern.compile(regularExpression);
        return createMatcherWithTimeout(stringToMatch, pattern, timeoutMillis);
    }

    public static Matcher createMatcherWithTimeout(String stringToMatch, Pattern regularExpressionPattern, int timeoutMillis) {
        CharSequence charSequence = new TimeoutRegexCharSequence(stringToMatch, timeoutMillis, stringToMatch,
                regularExpressionPattern.pattern());
        return regularExpressionPattern.matcher(charSequence);
    }

    private static class TimeoutRegexCharSequence implements CharSequence {

        private final CharSequence inner;

        private final int timeoutMillis;

        private final long timeoutTime;

        private final String stringToMatch;

        private final String regularExpression;

        public TimeoutRegexCharSequence(CharSequence inner, int timeoutMillis, String stringToMatch, String regularExpression) {
            super();
            this.inner = inner;
            this.timeoutMillis = timeoutMillis;
            this.stringToMatch = stringToMatch;
            this.regularExpression = regularExpression;
            timeoutTime = System.currentTimeMillis() + timeoutMillis;
        }

        public char charAt(int index) {
            if (System.currentTimeMillis() > timeoutTime) {
                throw new RuntimeException("Timeout occurred after " + timeoutMillis + "ms while processing regular expression '"
                                + regularExpression + "' on input '" + stringToMatch + "'!");
            }
            return inner.charAt(index);
        }

        public int length() {
            return inner.length();
        }

        public CharSequence subSequence(int start, int end) {
            return new TimeoutRegexCharSequence(inner.subSequence(start, end), timeoutMillis, stringToMatch, regularExpression);
        }

        @Override
        public String toString() {
            return inner.toString();
        }
    }

}

Thanks a lot to dawce for pointing me to this solution in answer to an unnecessary complicated question !

A: From Heritrix: (crawler.archive.org)
/**
 * CharSequence that noticed thread interrupts -- as might be necessary
 * to recover from a loose regex on unexpected challenging input.
 *
 * @author gojomo
 */
public class InterruptibleCharSequence implements CharSequence {
    CharSequence inner;
    // public long counter = 0;

    public InterruptibleCharSequence(CharSequence inner) {
        super();
        this.inner = inner;
    }

    public char charAt(int index) {
        if (Thread.interrupted()) { // clears flag if set
            throw new RuntimeException(new InterruptedException());
        }
        // counter++;
        return inner.charAt(index);
    }

    public int length() {
        return inner.length();
    }

    public CharSequence subSequence(int start, int end) {
        return new InterruptibleCharSequence(inner.subSequence(start, end));
    }

    @Override
    public String toString() {
        return inner.toString();
    }
}

Wrap your CharSequence with this one and Thread interrupts will work ...

A: A long-running pattern matching process can be stopped using the below method.

*

*Create StateFulCharSequence class which manages the state of pattern matching. When that state is changed, an exception is thrown on the next call to charAt method.

*That state change can be scheduled using ScheduledExecutorService with a required timeout.

*Here pattern matching is happening in the main thread and there is no need to check the thread interrupt state every time.
public class TimedPatternMatcher {
public static void main(String[] args) {
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    Pattern pattern = Pattern.compile("some regex pattern");
    StateFulCharSequence stateFulCharSequence = new StateFulCharSequence("some character sequence");
    Matcher matcher = pattern.matcher(stateFulCharSequence);
    executorService.schedule(stateFulCharSequence, 10, TimeUnit.MILLISECONDS);
    try {
        boolean isMatched = matcher.find();
    }catch (Exception e) {
        e.printStackTrace();
    }

}

/*
When this runnable is executed, it will set timeOut to true and pattern matching is stopped by throwing exception.
 */
public static class StateFulCharSequence implements CharSequence, Runnable{
    private CharSequence inner;

    private boolean isTimedOut = false;

    public StateFulCharSequence(CharSequence inner) {
        super();
        this.inner = inner;
    }

    public char charAt(int index) {
        if (isTimedOut) {
            throw new RuntimeException(new TimeoutException("Pattern matching timeout occurs"));
        }
        return inner.charAt(index);
    }

    @Override
    public int length() {
        return inner.length();
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return new StateFulCharSequence(inner.subSequence(start, end));
    }

    @Override
    public String toString() {
        return inner.toString();
    }

    public void setTimedOut() {
        this.isTimedOut = true;
    }

    @Override
    public void run() {
        this.isTimedOut = true;
    }
}}

A: Another workaround would be to limit the region of the matcher, then call find(), repeating until the thread is interrupted or a match is found.

A: Maybe what you need is a new lib which implements the NFA algorithm.
The NFA algorithm is hundreds times faster than the algorithm which is used by Java standard library.
And the Java std lib is sensitive to the input regexp, which may make your problem happen -- some input make the CPU run for years.
And the timeout can be set by the NFA algorithm through the steps it uses. It is effective than the Thread solution. Trust me I use thread timeout to a relative problem, it is horrible for performance. I finally fix the problem by modify the main loop of my algorithm implement. I insert some check point to the main loop to test the time.
The detail can be found here: https://swtch.com/~rsc/regexp/regexp1.html .

A: I included a counter in order to check every n reads of charAt, in order to reduce the overhead.
Notes:
Some people stated that carAt may not be call frequently enough. I just added the foo variable in order to demostrate how much charAt is called, and that it is frequent enough. If you're going to use this in production, remove that counter, as it will decrease performance and end up overflowing long if ran in a server for long time. In this example, charAt is called 30 million times every 0.8 secs or so (not tested with proper microbenchmarking conditions, it is just a proof of concept). You can set a lower checkInterval if you want higher precission, at the cost of performance (System.currentTimeMillis() > timeoutTime is more expensive than the if clause on the long run.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.goikosoft.test.RegexpTimeoutException;

/**
 * Allows to create timeoutable regular expressions.
 *
 * Limitations: Can only throw RuntimeException. Decreases performance.
 *
 * Posted by Kris in stackoverflow.
 *
 * Modified by dgoiko to  ejecute timeout check only every n chars.
 * Now timeout < 0 means no timeout.
 *
 * @author Kris https://stackoverflow.com/a/910798/9465588
 *
 */
public class RegularExpressionUtils {

    public static long foo = 0;

    // demonstrates behavior for regular expression running into catastrophic backtracking for given input
    public static void main(String[] args) {
        long millis = System.currentTimeMillis();
        // This checkInterval produces a < 500 ms delay. Higher checkInterval will produce higher delays on timeout.
        Matcher matcher = createMatcherWithTimeout(
                "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "(x+x+)+y", 10000, 30000000);
        try {
            System.out.println(matcher.matches());
        } catch (RuntimeException e) {
            System.out.println("Operation timed out after " + (System.currentTimeMillis() - millis) + " milliseconds");
        }
        System.out.print(foo);
    }

    public static Matcher createMatcherWithTimeout(String stringToMatch, String regularExpression, long timeoutMillis,
                                                      int checkInterval) {
        Pattern pattern = Pattern.compile(regularExpression);
        return createMatcherWithTimeout(stringToMatch, pattern, timeoutMillis, checkInterval);
    }

    public static Matcher createMatcherWithTimeout(String stringToMatch, Pattern regularExpressionPattern,
                                                    long timeoutMillis, int checkInterval) {
        if (timeoutMillis < 0) {
            return regularExpressionPattern.matcher(stringToMatch);
        }
        CharSequence charSequence = new TimeoutRegexCharSequence(stringToMatch, timeoutMillis, stringToMatch,
                regularExpressionPattern.pattern(), checkInterval);
        return regularExpressionPattern.matcher(charSequence);
    }

    private static class TimeoutRegexCharSequence implements CharSequence {

        private final CharSequence inner;

        private final long timeoutMillis;

        private final long timeoutTime;

        private final String stringToMatch;

        private final String regularExpression;

        private int checkInterval;

        private int attemps;

        TimeoutRegexCharSequence(CharSequence inner, long timeoutMillis, String stringToMatch,
                                  String regularExpression, int checkInterval) {
            super();
            this.inner = inner;
            this.timeoutMillis = timeoutMillis;
            this.stringToMatch = stringToMatch;
            this.regularExpression = regularExpression;
            timeoutTime = System.currentTimeMillis() + timeoutMillis;
            this.checkInterval = checkInterval;
            this.attemps = 0;
        }

        public char charAt(int index) {
            if (this.attemps == this.checkInterval) {
                foo++;
                if (System.currentTimeMillis() > timeoutTime) {
                    throw new RegexpTimeoutException(regularExpression, stringToMatch, timeoutMillis);
                }
                this.attemps = 0;
            } else {
                this.attemps++;
            }

            return inner.charAt(index);
        }

        public int length() {
            return inner.length();
        }

        public CharSequence subSequence(int start, int end) {
            return new TimeoutRegexCharSequence(inner.subSequence(start, end), timeoutMillis, stringToMatch,
                                                regularExpression, checkInterval);
        }

        @Override
        public String toString() {
            return inner.toString();
        }
    }

}

And the custom exception, so you can catch only THAT exception to avoid swalowing other RE Pattern / Matcher may throw.
public class RegexpTimeoutException extends RuntimeException {
    private static final long serialVersionUID = 6437153127902393756L;

    private final String regularExpression;

    private final String stringToMatch;

    private final long timeoutMillis;

    public RegexpTimeoutException() {
        super();
        regularExpression = null;
        stringToMatch = null;
        timeoutMillis = 0;
    }

    public RegexpTimeoutException(String message, Throwable cause) {
        super(message, cause);
        regularExpression = null;
        stringToMatch = null;
        timeoutMillis = 0;
    }

    public RegexpTimeoutException(String message) {
        super(message);
        regularExpression = null;
        stringToMatch = null;
        timeoutMillis = 0;
    }

    public RegexpTimeoutException(Throwable cause) {
        super(cause);
        regularExpression = null;
        stringToMatch = null;
        timeoutMillis = 0;
    }

    public RegexpTimeoutException(String regularExpression, String stringToMatch, long timeoutMillis) {
        super("Timeout occurred after " + timeoutMillis + "ms while processing regular expression '"
                + regularExpression + "' on input '" + stringToMatch + "'!");
        this.regularExpression = regularExpression;
        this.stringToMatch = stringToMatch;
        this.timeoutMillis = timeoutMillis;
    }

    public String getRegularExpression() {
        return regularExpression;
    }

    public String getStringToMatch() {
        return stringToMatch;
    }

    public long getTimeoutMillis() {
        return timeoutMillis;
    }

}

Based on Andreas' answer. Main credits should go for him and his source.

A: What about checking the user-submitted regex for "evil" patterns prior to execution using one or more regex patterns (this could be in to form of a method called prior to conditional execution of the regex):
This regex:
\(.+\+\)[\+\*]

Will match:
(a+)+
(ab+)+
([a-zA-Z]+)*

This Regex:
\((.+)\|(\1\?|\1{2,})\)\+

Will match:
(a|aa)+
(a|a?)+

This Regex:
\(\.\*.\)\{\d{2,}\}

Will match:
(.*a){x} for x \> 10

I may be a bit naive wrt Regex and Regex DoS, but I can't help but think that a little pre-screening for known "evil" patterns would go a long way toward preventing issues at execution time, especially if the regex in question is an input provided by an end user.  The patterns above are likely not refined enough, since I am far from an expert on regex.  It is just food for thought, since everything else I have found out there seems to indicate it can't be done, and focuses on either putting a time-out on the regex engine, or limiting the number of iterations it is allowed to execute.


text:
Q: Apache Camel - get property`s value from the body I have to get the value of a property from  the body of a POST call.
I want to POST a JSON of this type:
{"key"   : ["test:testValue"
            "keyTest:value"],
"address": "testAddress",
"type"   : "street"}

Before to save the entity I want to check if the value of "key" property contains a String with the value which contains the char ":" - some kind of validation.
At the same time I want to ensure the value of "type" is part of a list of Enumeration - some kind of validation also here.
I tried to use simple() or exchange - and validator() in the way to check if the value contains : - but without any success.
How I can get the value of a key from the body of the POST call?

A: A simple solution would be to first unmarshal the JSON to a POJO and then validate the POJO using the Bean Component(https://camel.apache.org/components/latest/bean-component.html).
Example:
.unmarshal().json(JsonLibrary.Jackson, Foo.class)
.bean(new CustomValidator(), "validateFoo")

The CustomValidator can be implemented like this(this is just an example, you can update it depending on you requirements):
public class CustomValidator {
    public void validateFoo(Exchange exchange) {
        Foo foo = exchange.getIn().getBody(Foo.class);
        if (foo == null || !validKeyList(foo.getKey())) {
            // throw exception
        }
    }

    private boolean validKeyList(List<String> values) {
        for (String value : values) {
            if (value.contains(":")) {
                return true;
            }
        }
        return false;
    }

}

For this to work you would need to add the camel-jackson library (https://mvnrepository.com/artifact/org.apache.camel/camel-jackson).
You can find information about JSON unmarshaling here: https://camel.apache.org/manual/latest/json.html.