Programs & Examples On #Eclipse wtp

Use this tag if you have a specific question about Eclipse Web Tools Platform (WTP) features and functionality. Do not use this tag on questions just because code was written or designed with Eclipse Web Tools.

What's in an Eclipse .classpath/.project file?

.project

When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.

.classpath

Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

I've just had same issue, this is what worked for me :

Note the message 'Server must be published with no modules present to make changes' on server dialog. So after removing the projects, re-publish your server, the option to set the server location should become re-enabled.

enter image description here

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Upgrading from Kepler to Luna worked for me.

I had just added some components for Java 1.8 support. It seems that they where not as compatible as I would like or that I mixed the wrong ones. It really caused a lot of problems. Trying to update the system reported errors as they couldn't fulfill some dependencies. Maven upgrades didn't work. Tried a lot of things.

So, if there is no reason to avoid the upgrade just add the luna repository to avalilable software sites (Luna http://download.eclipse.org/releases/luna/ ) and "check for updates". It is better to have all the components with the same version and there are some nice new features.

Getting an "ambiguous redirect" error

Does the path specified in ${OUPUT_RESULTS} contain any whitespace characters? If so, you may want to consider using ... >> "${OUPUT_RESULTS}" (using quotes).

(You may also want to consider renaming your variable to ${OUTPUT_RESULTS})

Java ArrayList - Check if list is empty

As simply as:

if (numbers.isEmpty()) {...}

Note that a quick look at the documentation would have given you that information.

git status shows modifications, git checkout -- <file> doesn't remove them

Another solution that may work for people, since none of the text options worked for me:

  1. Replace the content of .gitattributes with a single line: * binary. This tells git to treat every file as a binary file that it can't do anything with.
  2. Check that message for the offending files is gone; if it's not you can git checkout -- <files> to restore them to the repository version
  3. git checkout -- .gitattributes to restore the .gitattributes file to its initial state
  4. Check that the files are still not marked as changed.

Line Break in XML?

just use &lt;br&gt; at the end of your lines.

VBA check if file exists

I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it's not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA's standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

flutter corner radius with transparent background

class MyApp2 extends StatelessWidget {

  @override
  Widget build(BuildContext context) { 
    return MaterialApp( 
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        appBarTheme: AppBarTheme(
          elevation: 0,
          color: Colors.blueAccent,
        )
      ),
      title: 'Welcome to flutter ',
      home: HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  int number = 0;
  void _increment(){
   setState(() {
      number ++;
   });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blueAccent,
        appBar: AppBar(
          title: Text('MyApp2'), 
          leading: Icon(Icons.menu),
          // backgroundColor: Colors.blueAccent,

          ),
        body: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(200.0),
              topRight: Radius.circular(200)
            ), 
            color: Colors.white,
          ),
        )
      );
  }
}

Android: Share plain text using intent (to all messaging apps)

Use below method, just pass the subject and body as arguments of the method

public static void shareText(String subject,String body) {
    Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
    txtIntent .setType("text/plain");
    txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
    startActivity(Intent.createChooser(txtIntent ,"Share"));
}

Pass Hidden parameters using response.sendRedirect()

Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.

RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);

The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.

Change onclick action with a Javascript function

Do not invoke the method when assigning the new onclick handler.

Simply remove the parenthesis:

document.getElementById("a").onclick = Foo;

UPDATE (due to new information):

document.getElementById("a").onclick = function () { Foo(param); };

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

BULK INSERT with identity (auto-increment) column

Don't BULK INSERT into your real tables directly.

I would always

  1. insert into a staging table dbo.Employee_Staging (without the IDENTITY column) from the CSV file
  2. possibly edit / clean up / manipulate your imported data
  3. and then copy the data across to the real table with a T-SQL statement like:

    INSERT INTO dbo.Employee(Name, Address) 
       SELECT Name, Address
       FROM dbo.Employee_Staging
    

Tomcat is not deploying my web project from Eclipse

I have this similar problem where I'm able to start the tomcat server but however application not initialized or started, so I have Right clicked on my project --> Deployment Assembly --> Click 'Add' in the right side panel, select 'Java Build path entries' and click 'Next', Now select 'Maven dependencies' and click 'Finish'. Now I run the server and it started the application successfully.

enter image description here enter image description here
enter image description here

scrollTop jquery, scrolling to div with id?

try this:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

Change image source with JavaScript

Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
 <script>_x000D_
 _x000D_
 _x000D_
 $(document).ready(function() {_x000D_
 _x000D_
  $("#ambient").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#body").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  _x000D_
  _x000D_
 });_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="temperature" class="main_button center-block">_x000D_
    <div class="large_circle_button"> _x000D_
     <h2>Select<br/>Temperature</h2>_x000D_
     <img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
                    <!-- TODO <img src='images/dropsterilewater.png'  onclick='changeImage("images/dropsterilewater.png");'>_x000D_
                                <img src='images/imagecansterilesaline.png'  onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="ambient" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="body" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
    _x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Best way to implement keyboard shortcuts in a Windows Forms application?

The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click event handler of that menu entry.

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

Convert base class to derived class

You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Pattern if you want to do this in order to extend the functionality of an existing object.

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

How do I replace a character in a string in Java?

Escaping strings can be tricky - especially if you want to take unicode into account. I suppose XML is one of the simpler formats/languages to escape but still. I would recommend taking a look at the StringEscapeUtils class in Apache Commons Lang, and its handy escapeXml method.

Matplotlib scatter plot with different text at each data point

I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Which will generate the following graph: enter image description here

Debugging WebSocket in Google Chrome

Short answer for Chrome Version 29 and up:

  1. Open debugger, go to the tab "Network"
  2. Load page with websocket
  3. Click on the websocket request with upgrade response from server
  4. Select the tab "Frames" to see websocket frames
  5. Click on the websocket request again to refresh frames

How to move from one fragment to another fragment on click of an ImageView in Android?

Add this code where you want to click and load Fragment. I hope it's work for you.


Fragment fragment = new yourfragment();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

Find files and tar them (with spaces)

If you have multiple files or directories and you want to zip them into independent *.gz file you can do this. Optional -type f -atime

find -name "httpd-log*.txt" -type f -mtime +1 -exec tar -vzcf {}.gz {} \;

This will compress

httpd-log01.txt
httpd-log02.txt

to

httpd-log01.txt.gz
httpd-log02.txt.gz

SQL Server CTE and recursion example

I haven't tested your code, just tried to help you understand how it operates in comment;

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
    UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>    
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

The simplest example of a recursive CTE I can think of to illustrate its operation is;

;WITH Numbers AS
(
    SELECT n = 1
    UNION ALL
    SELECT n + 1
    FROM Numbers
    WHERE n+1 <= 10
)
SELECT n
FROM Numbers

Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.

A1: In this case, N is not a variable. N is an alias. It is the equivalent of SELECT 1 AS N. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE in T-SQL. I've included the analog of a simple CTE in Excel to try and illustrate in a more familiar way what is happening.

--  Outside
;WITH CTE (MyColName) AS
(
    SELECT 1
)
-- Inside
;WITH CTE AS
(
    SELECT 1 AS MyColName
    -- Or
    SELECT MyColName = 1  
    -- Etc...
)

Excel_CTE

Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager

A2:

Does this code answer your question?

--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS 
(
    SELECT 1,      'Keith',      NULL   UNION ALL
    SELECT 2,      'Josh',       1      UNION ALL
    SELECT 3,      'Robin',      1      UNION ALL
    SELECT 4,      'Raja',       2      UNION ALL
    SELECT 5,      'Tridip',     NULL   UNION ALL
    SELECT 6,      'Arijit',     5      UNION ALL
    SELECT 7,      'Amit',       5      UNION ALL
    SELECT 8,      'Dev',        6   
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
    --  Anchor
    SELECT   ID
            ,Name
            ,MgrID
            ,nLevel = 1
            ,Family = ROW_NUMBER() OVER (ORDER BY Name)
    FROM Employee
    WHERE MgrID IS NULL

    UNION ALL
    --  Recursive query
    SELECT   E.ID
            ,E.Name
            ,E.MgrID
            ,H.nLevel+1
            ,Family
    FROM Employee   E
    JOIN Hierarchy  H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel

Another one sql with tree structure

SELECT ID,space(nLevel+
                    (CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
                )+Name
FROM Hierarchy
ORDER BY Family, nLevel

What is difference between mutable and immutable String in java

In Java, all strings are immutable. When you are trying to modify a String, what you are really doing is creating a new one. However, when you use a StringBuilder, you are actually modifying the contents, instead of creating a new one.

How do I initialize a TypeScript Object with a JSON-Object?

TLDR: TypedJSON (working proof of concept)


The root of the complexity of this problem is that we need to deserialize JSON at runtime using type information that only exists at compile time. This requires that type-information is somehow made available at runtime.

Fortunately, this can be solved in a very elegant and robust way with decorators and ReflectDecorators:

  1. Use property decorators on properties which are subject to serialization, to record metadata information and store that information somewhere, for example on the class prototype
  2. Feed this metadata information to a recursive initializer (deserializer)

 

Recording Type-Information

With a combination of ReflectDecorators and property decorators, type information can be easily recorded about a property. A rudimentary implementation of this approach would be:

function JsonMember(target: any, propertyKey: string) {
    var metadataFieldKey = "__propertyTypes__";

    // Get the already recorded type-information from target, or create
    // empty object if this is the first property.
    var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});

    // Get the constructor reference of the current property.
    // This is provided by TypeScript, built-in (make sure to enable emit
    // decorator metadata).
    propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}

For any given property, the above snippet will add a reference of the constructor function of the property to the hidden __propertyTypes__ property on the class prototype. For example:

class Language {
    @JsonMember // String
    name: string;

    @JsonMember// Number
    level: number;
}

class Person {
    @JsonMember // String
    name: string;

    @JsonMember// Language
    language: Language;
}

And that's it, we have the required type-information at runtime, which can now be processed.

 

Processing Type-Information

We first need to obtain an Object instance using JSON.parse -- after that, we can iterate over the entires in __propertyTypes__ (collected above) and instantiate the required properties accordingly. The type of the root object must be specified, so that the deserializer has a starting-point.

Again, a dead simple implementation of this approach would be:

function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
    if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
        // No root-type with usable type-information is available.
        return jsonObject;
    }

    // Create an instance of root-type.
    var instance: any = new Constructor();

    // For each property marked with @JsonMember, do...
    Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
        var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];

        // Deserialize recursively, treat property type as root-type.
        instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
    });

    return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);

The above idea has a big advantage of deserializing by expected types (for complex/object values), instead of what is present in the JSON. If a Person is expected, then it is a Person instance that is created. With some additional security measures in place for primitive types and arrays, this approach can be made secure, that resists any malicious JSON.

 

Edge Cases

However, if you are now happy that the solution is that simple, I have some bad news: there is a vast number of edge cases that need to be taken care of. Only some of which are:

  • Arrays and array elements (especially in nested arrays)
  • Polymorphism
  • Abstract classes and interfaces
  • ...

If you don't want to fiddle around with all of these (I bet you don't), I'd be glad to recommend a working experimental version of a proof-of-concept utilizing this approach, TypedJSON -- which I created to tackle this exact problem, a problem I face myself daily.

Due to how decorators are still being considered experimental, I wouldn't recommend using it for production use, but so far it served me well.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Filter values only if not null using lambda in Java8

In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

cars.stream()
    .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

cars.stream()
    .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .map(car -> car.getName())
    .filter(carName -> Objects.nonNull(carName))
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

cars.stream()
    .filter(Objects::nonNull)
    .map(Car::getName)        // Assume the class name for car is Car
    .filter(Objects::nonNull)
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .filter(car -> Objects.nonNull(car.getName()))
    .filter(car -> car.getName().startsWith("M"))
    .collect(Collectors.toList());

How to install numpy on windows using pip install?

First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.

How to connect to MongoDB in Windows?

Create default db folder.

c:\data\db

and also log folder

c:\data\log\mongo.log

or use following commands in command-prompt

mkdir c:\data\log    
mkdir c:\data\db

Styling an anchor tag to look like a submit button

Using CSS:

.button {
    display: block;
    width: 115px;
    height: 25px;
    background: #4E9CAF;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    color: white;
    font-weight: bold;
}

<a href="some_url" class="button ">Cancel</a>

Rollback one specific migration in Laravel

It's quite easy to roll back just a specific migration.
Since the command php artisan migrate:rollback, undo the last database migration, and the order of the migrations execution is stored in the batch field in the migrations table.

You can edit the batch value of the migration that you want to rollback and set it as the higher. Then you can rollback that migration with a simple:

php artisan migrate:rollback

After editing the same migration you can execute it again with a simple

php artisan migrate

NOTICE: if two or more migrations have the same higher value, they will be all rolled back at the same time.

Remove duplicates from a list of objects based on property in Java 8

Another solution is to use a Predicate, then you can use this in any filter:

public static <T> Predicate<T> distinctBy(Function<? super T, ?> f) {
  Set<Object> objects = new ConcurrentHashSet<>();
  return t -> objects.add(f.apply(t));
}

Then simply reuse the predicate anywhere:

employees.stream().filter(distinctBy(e -> e.getId));

Note: in the JavaDoc of filter, which says it takes a stateless Predicte. Actually, this works fine even if the stream is parallel.


About other solutions:

1) Using .collect(Collectors.toConcurrentMap(..)).values() is a good solution, but it's annoying if you want to sort and keep the order.

2) stream.removeIf(e->!seen.add(e.getID())); is also another very good solution. But we need to make sure the collection implemented removeIf, for example it will throw exception if we construct the collection use Arrays.asList(..).

c++ exception : throwing std::string

Simplest way to throw an Exception in C++:

#include <iostream>
using namespace std;
void purturb(){
    throw "Cannot purturb at this time.";
}
int main() {
    try{
        purturb();
    }
    catch(const char* msg){
        cout << "We caught a message: " << msg << endl;
    }
    cout << "done";
    return 0;
}

This prints:

We caught a message: Cannot purturb at this time.
done

If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

How to generate a Dockerfile from an image?

I somehow absolutely missed the actual command in the accepted answer, so here it is again, bit more visible in its own paragraph, to see how many people are like me

$ docker history --no-trunc <IMAGE_ID>

Call break in nested if statements

If you label the if statement you can use break.

breakme: if (condition) {
    // Do stuff

    if (condition2){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

You can even label and break plain blocks.

breakme: {
    // Do stuff

    if (condition){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.

( function() {
   // Do stuff

   if ( condition1 ) {
       // Do stuff 
   } else {
       return;
   }

   // Do other stuff
}() );

How can I show an image using the ImageView component in javafx and fxml?

The Code part :

Image imProfile = new Image(getClass().getResourceAsStream("/img/profile128.png"));

ImageView profileImage=new ImageView(imProfile);

in a javafx maven:

enter image description here

Android: show soft keyboard automatically when focus is on an EditText

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

How to secure the ASP.NET_SessionId cookie?

Here is a code snippet taken from a blog article written by Anubhav Goyal:

// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
    foreach (string s in Response.Cookies.AllKeys)
    {
        if (s == FormsAuthentication.FormsCookieName || "asp.net_sessionid".Equals(s, StringComparison.InvariantCultureIgnoreCase))
        {
             Response.Cookies[s].Secure = true;
        }
    }
}

Adding this to the EndRequest event handler in the global.asax should make this happen for all page calls.

Note: An edit was proposed to add a break; statement inside a successful "secure" assignment. I've rejected this edit based on the idea that it would only allow 1 of the cookies to be forced to secure and the second would be ignored. It is not inconceivable to add a counter or some other metric to determine that both have been secured and to break at that point.

Adding an onclick function to go to url in JavaScript?

In case you're dealing with <a> tag, and you want to interrupt going to the default href you should use this instead.

Go to default url (yahoo):

<a href="https://yahoo.com" onclick="location.href='https://google.com';"> 

Go to new url (google) onclick:

<a href="https://yahoo.com" onclick="this.href='https://google.com';">

By using this you're interrupting the current browser onclick event and changing href before continuing to default behaviour of <a href='...

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

Get DOS path instead of Windows path

A someone more direct answer is to fix the bug.

%SPARK_HOME%\bin\spark-class2.cmd; Line 54
Broken: set RUNNER="%JAVA_HOME%\bin\java"
Windows Style: set "RUNNER=%JAVA_HOME%\bin\java"

Otherwise, the RUNNER ends up with quotes, and the command "%RUNNER%" -Xmx128m ... ends up with double-quotes. The result is that the Program and File are treated as separate parameters.

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

the error i received was:

cockpit.socket: Failed to listen on sockets: Address already in use

the fix I discovered is:

  1. I had to disable selinux
  2. in /usr/lib/systemd/system/cockpit service i changed the line :

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
    

    to:

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws 
    

so as you can see i took out the argument about selinux then i ran:

systemctl daemon-reload
systemctl start cockpit.service

then I browsed to:

I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.

this is all on a fedora25 machine. the 9090 port had already been added using firewall-cmd

Explicit vs implicit SQL joins

On some databases (notably Oracle) the order of the joins can make a huge difference to query performance (if there are more than two tables). On one application, we had literally two orders of magnitude difference in some cases. Using the inner join syntax gives you control over this - if you use the right hints syntax.

You didn't specify which database you're using, but probability suggests SQL Server or MySQL where there it makes no real difference.

How do you remove an array element in a foreach loop?

A better solution is to use the array_filter function:

$display_related_tags =
    array_filter($display_related_tags, function($e) use($found_tag){
        return $e != $found_tag['name'];
    });

As the php documentation reads:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

For what it's worth, I do this:

    <!-- Favicon - Generic -->
    <link rel="icon" href="path/favicon-32_x_32.png" sizes="32x32">
    <link rel="icon" href="path/favicon-57_x_57.png" sizes="57x57">
    <link rel="icon" href="path/favicon-76_x_76.png" sizes="76x76">
    <link rel="icon" href="path/favicon-96_x_96.png" sizes="96x96">
    <link rel="icon" href="path/favicon-128_x_128.png" sizes="128x128">
    <link rel="icon" href="path/favicon-192_x_192.png" sizes="192x192">
    <link rel="icon" href="path/favicon-228_x_228.png" sizes="228x228">
    <!-- Favicon - Android -->
    <link rel="shortcut icon" href="path/favicon-196_x_196.png" sizes="196x196">
    <!-- Favicon - iOS -->
    <link rel="apple-touch-icon" href="path/favicon-120_x_120.png" sizes="120x120">
    <link rel="apple-touch-icon" href="path/favicon-152_x_152.png" sizes="152x152">
    <link rel="apple-touch-icon" href="path/favicon-180_x_180.png" sizes="180x180">

And I still keep the favicon.ico in root.

Does Python support short-circuiting?

Short-circuiting behavior in operator and, or:

Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.

>>> def fun(i):
...     print "executed"
...     return i
... 

One can observe the Python's short-circuiting behavior of and, or operators in the following example:

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed 
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
0

Note: The following values are considered by the interpreter to mean false:

        False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any(), all():

Python's any() and all() functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.

The function any() checks if any element is True. It stops executing as soon as a True is encountered and returns True.

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])   
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

The function all() checks all elements are True and stops executing as soon as a False is encountered:

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

Short-circuiting behavior in Chained Comparison:

Additionally, in Python

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True 
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

Edit:
One more interesting point to note :- Logical and, or operators in Python returns an operand's value instead of a Boolean (True or False). For example:

Operation x and y gives the result if x is false, then x, else y

Unlike in other languages e.g. &&, || operators in C that return either 0 or 1.

Examples:

>>> 3 and 5    # Second operand evaluated and returned 
5                   
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned 

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples:

>>> 2 or 5    # left most operand bool(2) == True
2    
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'. You could use an if statement, but you could also state things very succinctly:

In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name: 

In [172]: name
Out[172]: '<Unknown>'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>' is assigned to name.

IPython Notebook save location

Just cd to your working folder and then start the IPython notebook server. This way you can be mobile.

There was no endpoint listening at (url) that could accept the message

Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.

Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:

  1. Open the IIS
  2. Click your site and/or your mapped application
  3. Click on Feature view and click Request Filtering
  4. Click - Edit Feature Settings.

Edit Feature Settings

I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests

html script src="" triggering redirection with button

Your foldername is scripts ?

Change

<script src="../Script/login.js">

to

<script src='scripts/login.js' type='text/javascript'></script>

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

Convert datetime to valid JavaScript date

You can use get methods:

_x000D_
_x000D_
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

Is there a function to round a float in C or do I need to write my own?

#include <math.h>

double round(double x);
float roundf(float x);

Don't forget to link with -lm. See also ceil(), floor() and trunc().

How to set selected value of jquery select2?

You should use:

var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');

// For set multi selected values
var data =  [];//Array Ids
var option =  [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
    // append the new option
    $("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');

    // get a list of selected values if any - or create an empty array
    var selectedValues = $("#EventId").val();
    if (selectedValues == null) {
        selectedValues = new Array();
    }
    selectedValues.push(response.id);   // add the newly created option to the list of selected items
    $("#EventId").val(selectedValues).trigger('change');   // have select2 do it's thing
});

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

SQL Query to find the last day of the month

I know this question was for SQL Server 2005, but I thought I'd mention- as of SQL 2012, there now is an EOMONTH() function that gets the last day of the month. To get it in the format specified by the original asker you'd have to cast to a datetime.

SELECT CAST(eomonth(GETDATE()) AS datetime)

How do you run multiple programs in parallel from a bash script?

How about:

prog1 & prog2 && fg

This will:

  1. Start prog1.
  2. Send it to background, but keep printing its output.
  3. Start prog2, and keep it in foreground, so you can close it with ctrl-c.
  4. When you close prog2, you'll return to prog1's foreground, so you can also close it with ctrl-c.

How do I detect "shift+enter" and generate a new line in Textarea?

Here is an AngularJS solution using ng-keyup if anyone has the same issue using AngularJS.

ng-keyup="$event.keyCode == 13 && !$event.shiftKey && myFunc()"

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Surprise to see no one mentioned about event.preventDefault()

$("input[type=file]").mouseover(function(event) {
    event.preventDefault();
    // This will disable the default behavior of browser
 });

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

Increasing Google Chrome's max-connections-per-server limit to more than 6

There doesn't appear to be an external way to hack the behaviour of the executables.

You could modify the Chrome(ium) executables as this information is obviously compiled in. That approach brings a lot of problems with support and automatic upgrades so you probably want to avoid doing that. You also need to understand how to make the changes to the binaries which is not something most people can pick up in a few days.

If you compile your own browser you are creating a support issue for yourself as you are stuck with a specific revision. If you want to get new features and bug fixes you will have to recompile. All of this involves tracking Chrome development for bugs and build breakages - not something that a web developer should have to do.

I'd follow @BenSwayne's advice for now, but it might be worth thinking about doing some of the work outside of the client (the web browser) and putting it in a background process running on the same or different machines. This process can handle many more connections and you are just responsible for getting the data back from it. Since it is local(ish) you'll get results back quickly even with minimal connections.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To handle null Map keys, some custom serialization is necessary, as best I understand.

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

Unable to open debugger port in IntelliJ

You may have to change the debugger port if your port is already used by another program. To do so:

  • Run
  • Edit Configurations
  • Startup/Connection tab
  • Debug
  • Change the port here

Or, maybe in other versions:

  • Run
  • Edit Configurations
  • Remote > Remote debug in the list on the left
  • Configuration tab, Settings section
  • Port: change the port here

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

Try upgrading your node to latest version.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

version 0.4 may not work properly.

Python datetime to string without microsecond component

>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'

Is it possible to force Excel recognize UTF-8 CSV files automatically?

As I posted on http://thinkinginsoftware.blogspot.com/2017/12/correctly-generate-csv-that-excel-can.html:

Tell the software developer in charge of generating the CSV to correct it. As a quick workaround you can use gsed to insert the UTF-8 BOM at the beginning of the string:

gsed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' file.csv

This command inserts the UTF-4 BOM if not present. Therefore it is an idempotent command. Now you should be able to double click the file and open it in Excel.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this:

UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
   Test1.dbo.Employee.EmployeeID = emp2.EmployeeID

From your post, I'm not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that's what my query does), or the other way around (since you mention the db on Test1 was the new table......)

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

How to monitor network calls made from iOS Simulator

A free and open source proxy tool that runs easily on a Mac is mitmproxy.

The website includes links to a Mac binary, as well as the source code on Github.

The docs contain a very helpful intro to loading a cert into your test device to view HTTPS traffic.

Not quite as GUI-tastic as Charles, but it does everything I need and its free and maintained. Good stuff, and pretty straightforward if you've used some command line tools before.

UPDATE: I just noticed on the website that mitmproxy is available as a homebrew install. Couldn't be easier.

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The addition of a string literal with an std::string yields another std::string. system expects a const char*. You can use std::string::c_str() for that:

string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());

Using R to list all files with a specified extension

I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:

files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]

First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.

I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.

What is the C++ function to raise a number to a power?

Many answers have suggested pow() or similar alternatives or their own implementations. However, given the examples (2^1, 2^2 and 2^3) in your question, I would guess whether you only need to raise 2 to an integer power. If this is the case, I would suggest you to use 1 << n for 2^n.

How to cast List<Object> to List<MyClass>

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

you must be sure that at runtime the list contains nothing but Customer objects.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

There is an easy way with Sharpeserializer (open source) :

http://www.sharpserializer.com/

It can directly serialize/de-serialize dictionary.

There is no need to mark your object with any attribute, nor do you have to give the object type in the Serialize method (See here ).

To install via nuget : Install-package sharpserializer

Then it is very simple :

Hello World (from the official website):

// create fake obj
var obj = createFakeObject();

// create instance of sharpSerializer
// with standard constructor it serializes to xml
var serializer = new SharpSerializer();

// serialize
serializer.Serialize(obj, "test.xml");

// deserialize
var obj2 = serializer.Deserialize("test.xml");

How to remove selected commit log entries from a Git repository while keeping their changes?

I find this process much safer and easier to understand by creating another branch from the SHA1 of A and cherry-picking the desired changes so I can make sure I'm satisfied with how this new branch looks. After that, it is easy to remove the old branch and rename the new one.

git checkout <SHA1 of A>
git log #verify looks good
git checkout -b rework
git cherry-pick <SHA1 of D>
....
git log #verify looks good
git branch -D <oldbranch>
git branch -m rework <oldbranch>

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

SSL Error: CERT_UNTRUSTED while using npm command

I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:

sudo apt-get update
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install nodejs -y

Installation instructions for more versions and systems can be found in the following link:

https://github.com/nodesource/distributions/blob/master/README.md

How to get the value from the GET parameters?

this question has too many answers, so i'm adding another one.

/**
 * parses and returns URI query parameters 
 * 
 * @param {string} param parm
 * @param {bool?} asArray if true, returns an array instead of a scalar 
 * @returns {Object|Array} 
 */
function getURIParameter(param, asArray) {
    return document.location.search.substring(1).split('&').reduce(function(p,c) {
        var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
        if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
        return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
    }, []);
}

usage:

getURIParameter("id")  // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids

this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

How to put a delay on AngularJS instant search?

I solved this problem with a directive that basicly what it does is to bind the real ng-model on a special attribute which I watch in the directive, then using a debounce service I update my directive attribute, so the user watch on the variable that he bind to debounce-model instead of ng-model.

.directive('debounceDelay', function ($compile, $debounce) {
return {
  replace: false,
  scope: {
    debounceModel: '='
  },
  link: function (scope, element, attr) {
    var delay= attr.debounceDelay;
    var applyFunc = function () {
      scope.debounceModel = scope.model;
    }
    scope.model = scope.debounceModel;
    scope.$watch('model', function(){
      $debounce(applyFunc, delay);
    });
    attr.$set('ngModel', 'model');
    element.removeAttr('debounce-delay'); // so the next $compile won't run it again!

   $compile(element)(scope);
  }
};
});

Usage:

<input type="text" debounce-delay="1000" debounce-model="search"></input>

And in the controller :

    $scope.search = "";
    $scope.$watch('search', function (newVal, oldVal) {
      if(newVal === oldVal){
        return;
      }else{ //do something meaningful }

Demo in jsfiddle: http://jsfiddle.net/6K7Kd/37/

the $debounce service can be found here: http://jsfiddle.net/Warspawn/6K7Kd/

Inspired by eventuallyBind directive http://jsfiddle.net/fctZH/12/

Reset input value in angular 2

  1. check the @viewchild in your .ts

    @ViewChild('ngOtpInput') ngOtpInput:any;
    
  2. set the below code in your method were you want the fields to be clear.

    yourMethod(){
        this.ngOtpInput.setValue(yourValue);
    }
    

T-SQL to list all the user mappings with database roles/permissions for a Login

CREATE TABLE #tempww (
    LoginName nvarchar(max),
    DBname nvarchar(max),
    Username nvarchar(max), 
    AliasName nvarchar(max)
)

INSERT INTO #tempww 
EXEC master..sp_msloginmappings 

-- display results
SELECT * 
FROM   #tempww 
ORDER BY dbname, username

-- cleanup
DROP TABLE #tempww

Codeigniter $this->input->post() empty while $_POST is working correctly

Upgrading from 2.2.x to 3.0.x -- reason post method fails. If you are upgrading CI 3.x, need to keep the index_page in config file. Also check the .htaccess file for mod_rewrite. CI_3.x

$config['index_page'] = ''; // ci 2.x
$config['index_page'] = 'index.php'; // ci 3.x

My .htaccess

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
 ErrorDocument 404 /index.php
</IfModule>

How can I use Python to get the system hostname?

If I'm correct, you're looking for the socket.gethostname function:

>> import socket
>> socket.gethostname()
'terminus'

WARNING: sanitizing unsafe style value url

Based on the docs at https://angular.io/api/platform-browser/DomSanitizer, the right way to do this seems to be to use sanitize. At least in Angular 7 (don't know if this changed from before). This worked for me:

import { Component, OnInit, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
    private sanitizer: DomSanitizer
) { }

this.sanitizer.sanitize(SecurityContext.STYLE, 'url(' + this.image + ')');

Re SecurityContext, see https://angular.io/api/core/SecurityContext. Basically it's just this enum:

enum SecurityContext {
  NONE: 0
  HTML: 1
  STYLE: 2
  SCRIPT: 3
  URL: 4
  RESOURCE_URL: 5
}

Singleton: How should it be used

Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.

If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.

Multiprocessing: How to use Pool.map on a function defined in a class?

I know that this question was asked 8 years and 10 months ago but I want to present you my solution:

from multiprocessing import Pool

class Test:

    def __init__(self):
        self.main()

    @staticmethod
    def methodForMultiprocessing(x):
        print(x*x)

    def main(self):
        if __name__ == "__main__":
            p = Pool()
            p.map(Test.methodForMultiprocessing, list(range(1, 11)))
            p.close()

TestObject = Test()

You just need to make your class function into a static method. But it's also possible with a class method:

from multiprocessing import Pool

class Test:

    def __init__(self):
        self.main()

    @classmethod
    def methodForMultiprocessing(cls, x):
        print(x*x)

    def main(self):
        if __name__ == "__main__":
            p = Pool()
            p.map(Test.methodForMultiprocessing, list(range(1, 11)))
            p.close()

TestObject = Test()

Tested in Python 3.7.3

How to open URL in Microsoft Edge from the command line?

Windows 10: Create a shortcut with this destination:

%windir%\system32\cmd.exe /c "start microsoft-edge:https://twitter.com"

How to get to a particular element in a List in java?

The List interface supports random access via the get method - to get line 0, use list.get(0). You'll need to use array access on that, ie, lines.get(0)[0] is the first element of the first line.

See the javadoc here.

How to use the PRINT statement to track execution as stored procedure is running?

Can I just ask about the long term need for this facility - is it for debuging purposes?

If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.

Just my opinion, but I prefer the debugger approach - for code and databases.

UnicodeDecodeError when reading CSV file in Pandas with Python

read_csv takes an encoding option to deal with files in different formats. I mostly use read_csv('file', encoding = "ISO-8859-1"), or alternatively encoding = "utf-8" for reading, and generally utf-8 for to_csv.

You can also use one of several alias options like 'latin' instead of 'ISO-8859-1' (see python docs, also for numerous other encodings you may encounter).

See relevant Pandas documentation, python docs examples on csv files, and plenty of related questions here on SO. A good background resource is What every developer should know about unicode and character sets.

To detect the encoding (assuming the file contains non-ascii characters), you can use enca (see man page) or file -i (linux) or file -I (osx) (see man page).

Decompile .smali files on an APK

My recommendation is Virtuous Ten Studio. The tool is free but they suggest a donation. It combines all the necessary steps (unpacking APK, baksmaliing, decompiling, etc.) into one easy-to-use UI-based import process. Within five minutes you should have Java source code, less than it takes to figure out the command line options of one of the above mentioned tools.

Decompiling smali to Java is an inexact process, especially if the smali artifacts went through an obfuscator. You can find several decompilers on the web but only some of them are still maintained. Some will give you better decompiled code than others. Read "better" as in "more understandable" than others. Don't expect that the reverse-engineered Java code will compile out of the box. Virtuous Ten Studio comes with multiple free Java decompilers built-in so you can easily try out different decompilers (the "Generate Java source" step) to see which one gives you the best results, saving you the time to find those decompilers yourself and figure out how to use them. Amongst them is CFR, which is one of the few free and still maintained decompilers.

As output you receive, amongst other things, a folder structure that contains all the decompiled Java source code. You can then import this into IntelliJ IDEA or Eclipse for further editing, analysis (e.g. Go to definition, Find usages), etc.

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

List files recursively in Linux CLI with path relative to the current directory

You could create a shell function, e.g. in your .zshrc or .bashrc:

filepath() {
    echo $PWD/$1
}

filepath2() {
    for i in $@; do
        echo $PWD/$i
    done
}

The first one would work on single files only, obviously.

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

I solved the same problem. I've just added JSTL-1.2.jar to /apache-tomcat-x.x.x/lib and set scope to provided in maven pom.xml:

 <dependency>
     <groupId>jstl</groupId>
     <artifactId>jstl</artifactId>
     <version>1.2</version>
     <scope>provided</scope>
 </dependency>

Difference between array_push() and $array[] =

I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:

     for($i = 0; $i < 10; $i++){
          array_push($arr, $i, $i*2, $i*3, $i*4, ...)
     }

instead of:

     for($i = 0; $i < 10; $i++){
         $arr[] = $i;
         $arr[] = $i*2;
         $arr[] = $i*3;
         $arr[] = $i*4;
         ...
     }

edit- Forgot to close the bracket for the for conditional

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

How to change password using TortoiseSVN?

If your administrator changed your password, and Windows 10 still stores your old password you will not be asked for a new password. Windows 10 will use the stored old password, and authentication will fail.

You can delete your old password by

  1. Click Start > Control Panel > User Accounts > Manage your credentials
  2. Windows credentials
  3. Modify or delete the stored password

If you delete a password, when you try to use SVN, you will be asked for the new password.

What's the difference between next() and nextLine() methods from Scanner class?

In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.

Lets have a look at following snippet of code

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.next();
    }

when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as

Input as :- abcd abcd or

Input as :-

abcd

abcd

Output will be like abcd

abcd

But if in same code we replace next() method by nextLine()

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.nextLine();
    }

Then if you enter input on prompt as - abcd abcd

Output is :-

abcd abcd

and if you enter the input on prompt as abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)

Output is:-

abcd

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

for Xcode 8:

What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.

Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.

I once saved over 50GB doing this since I did so much testing on older iOS versions.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How to define a Sql Server connection string to use in VB.NET?

Use the following Imports

Imports System.Data.SqlClient
Imports System.Data.Sql

Public SQLConn As New SqlConnection With {.ConnectionString = "Server=Desktop1[enter image description here][1];Database=Infostudio; Trusted_Connection=true;"}

Full string: enter image description here

Best way to detect when a user leaves a web page?

Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:

// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null

global.self.addEventListener('fetch', event => {
  clearTimeout(liveTimeout)
  liveTimeout = setTimeout(() => {
    console.log('User left page')
    // handle page leave
  }, liveTimeoutDelay)
  // Forward any events except for hearbeat events
  if (event.request.url.endsWith('/heartbeat')) {
    event.respondWith(
      new global.Response('Still here')
    )
  }
})

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

How to check if two arrays are equal with JavaScript?

Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:

[1, 2, 3].toString() == [1, 2, 3].toString()
true
[1, 2, 3,].toString() == [1, 2, 3].toString()
true
[1,2,3].toString() == [1, 2, 3].toString()
true

However, this doesn't work for mode advanced cases such as:

[[1,2],[3]].toString() == [[1],[2,3]].toString()
true

It depends what you need.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

For those who is still using @Paul Burke's code with Android SDK version 23 and above, if your project met the error saying that you are missing EXTERNAL_PERMISSION, and you are very sure you have already added user-permission in your AndroidManifest.xml file. That's because you may in Android API 23 or above and Google make it necessary to guarantee permission again while you make the action to access the file in runtime.

That means: If your SDK version is 23 or above, you are asked for READ & WRITE permission while you are selecting the picture file and want to know the URI of it.

And following is my code, in addition to Paul Burke's solution. I add these code and my project start to work fine.

private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static final String[] PERMISSINOS_STORAGE = {
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE
};

public static void verifyStoragePermissions(Activity activity) {
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                activity,
                PERMISSINOS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

And in your activity&fragment where you are asking for the URI:

private void pickPhotoFromGallery() {

    CompatUtils.verifyStoragePermissions(this);
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    // startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
    startActivityForResult(Intent.createChooser(intent, "????"),
            REQUEST_PHOTO_LIBRARY);
}

In my case, CompatUtils.java is where I define the verifyStoragePermissions method (as static type so I can call it within other activity).

Also it should make more sense if you make an if state first to see whether the current SDK version is above 23 or not before you call the verifyStoragePermissions method.

window.open with headers

Can I control the HTTP headers sent by window.open (cross browser)?

No

If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?

  • You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
  • You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.

I need some cunning hacks...

It might help if you described the problem instead of asking if possible solutions would work.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

The command to change the shell at startup is chsh -s <path_to_shell>. The default shells in mac OS X are installed inside the bin directory so if you want to change to the default zsh then you would use the following

chsh -s /bin/zsh

If you're using different version of zsh then you might have to add that version to /etc/shells to avoid the nonstandard shell message. For example if you want home-brew's version of zsh then you have to add /usr/local/bin/zsh to the aforementioned file which you can do in one command sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" and then run

chsh -s /usr/local/bin/zsh

Or if you want to do the whole thing in one command just copy and paste this if you have zsh already installed

sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" && chsh -s /usr/local/bin/zsh

Match the path of a URL, minus the filename extension

Regular expression for matching everything after "net" and before ".php":

$pattern = "net([a-zA-Z0-9_]*)\.php"; 

In the above regular expression, you can find the matching group of characters enclosed by "()" to be what you are looking for.

Hope it's useful.

What is the correct value for the disabled attribute?

  • For XHTML, <input type="text" disabled="disabled" /> is the valid markup.
  • For HTML5, <input type="text" disabled /> is valid and used by W3C on their samples.
  • In fact, both ways works on all major browsers.

org.xml.sax.SAXParseException: Content is not allowed in prolog

If all else fails, open the file in binary to make sure there are no funny characters [3 non printable characters at the beginning of the file that identify the file as utf-8] at the beginning of the file. We did this and found some. so we converted the file from utf-8 to ascii and it worked.

OpenCV !_src.empty() in function 'cvtColor' error

  • Most probably there is an error in loading the image, try checking directory again.
  • Print the image to confirm if it actually loaded or not

Uncaught TypeError: Cannot set property 'value' of null

You don't have an element with the id u.That's why the error occurs. Note that the global variable document.getElementById("u").value means you are trying to get the value of input element with name u and its not defined in your code.

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

Where does MySQL store database files on Windows and what are the names of the files?

In Windows 7, the MySQL database is stored at

C:\ProgramData\MySQL\MySQL Server 5.6\data

Note: this is a hidden folder. And my example is for MySQL Server version 5.6; change the folder name based on your version if different.

It comes in handy to know this location because sometimes the MySQL Workbench fails to drop schemas (or import databases). This is mostly due to the presence of files in the db folders that for some reason could not be removed in an earlier process by the Workbench. Remove the files using Windows Explorer and try again (dropping, importing), your problem should be solved.

Hope this helps :)

iterating through Enumeration of hastable keys throws NoSuchElementException error

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

How to create id with AUTO_INCREMENT on Oracle?

Here is complete solution w.r.t exception/error handling for auto increment, this solution is backward compatible and will work on 11g & 12c, specifically if application is in production.

Please replace 'TABLE_NAME' with your appropriate table name

--checking if table already exisits
BEGIN
    EXECUTE IMMEDIATE 'DROP TABLE TABLE_NAME';
    EXCEPTION WHEN OTHERS THEN NULL;
END;
/

--creating table
CREATE TABLE TABLE_NAME (
       ID NUMBER(10) PRIMARY KEY NOT NULL,
       .
       .
       .
);

--checking if sequence already exists
BEGIN
    EXECUTE IMMEDIATE 'DROP SEQUENCE TABLE_NAME_SEQ';
    EXCEPTION WHEN OTHERS THEN NULL;
END;

--creating sequence
/
CREATE SEQUENCE TABLE_NAME_SEQ START WITH 1 INCREMENT BY 1 MINVALUE 1 NOMAXVALUE NOCYCLE CACHE 2;

--granting rights as per required user group
/
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE_NAME TO USER_GROUP;

-- creating trigger
/
CREATE OR REPLACE TRIGGER TABLE_NAME_TS BEFORE INSERT OR UPDATE ON TABLE_NAME FOR EACH ROW
BEGIN    
    -- auto increment column
    SELECT TABLE_NAME_SEQ.NextVal INTO :New.ID FROM dual;

    -- You can also put some other required default data as per need of your columns, for example
    SELECT SYS_CONTEXT('USERENV', 'SESSIONID') INTO :New.SessionID FROM dual;
    SELECT SYS_CONTEXT('USERENV','SERVER_HOST') INTO :New.HostName FROM dual;
    SELECT SYS_CONTEXT('USERENV','OS_USER') INTO :New.LoginID FROM dual;    
    .
    .
    .
END;
/

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

How to override equals method in Java

I'm not sure of the details as you haven't posted the whole code, but:

  • remember to override hashCode() as well
  • the equals method should have Object, not People as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.
  • you can use instanceof to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
  • equals is used for all objects, but not primitives. I think you mean age is an int (primitive), in which case just use ==. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.

See What issues should be considered when overriding equals and hashCode in Java? for more details.

Save PL/pgSQL output from PostgreSQL to a CSV file

Do you want the resulting file on the server, or on the client?

Server side

If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;

This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

  1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
  2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.


Client side

The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

\copy (Select * From foo) To '/tmp/test.csv' With CSV

Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

From the docs:

Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.

How to best display in Terminal a MySQL SELECT returning too many fields?

You might also find this useful (non-Windows only):

mysql> pager less -SFX
mysql> SELECT * FROM sometable;

This will pipe the outut through the less command line tool which - with these parameters - will give you a tabular output that can be scrolled horizontally and vertically with the cursor keys.

Leave this view by hitting the q key, which will quit the less tool.

JavaScript file not updating no matter what I do

Don't forget to check any errors in webpack compilation. Sometimes the application.js in app/javascript/packs/ doesn't reload due to webpack compilation error.

Random character generator with a range of (A..Z, 0..9) and punctuation

You should first make a String that holds all of the letters/numbers that you want.
Then, make a Random. e. g. Random rnd = new Random;
Finally, make something that actually gets a random character from your String containing your alphabet.
For example,

import java.util.Random;

public class randomCharacter {
    public static void main(String[] args) {
        String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?/.,";
        Random rnd = new Random();
        char char = alphabet.charAt(rnd.nextInt(alphabet.length()));
        // do whatever you want with the character
    }
}

See this.
It's where I got this info from.

How to Create simple drag and Drop in angularjs

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

Code is here: http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

Combining multiple commits before pushing in Git

There are quite a few working answers here, but I found this the easiest. This command will open up an editor, where you can just replace pick with squash in order to remove/merge them into one

git rebase -i HEAD~4

where, 4 is the number of commits you want to squash into one. This is explained here as well.

Scrolling a div with jQuery

I know this is ages old, but upon searching for something similar this morning, and reading up on Atømix' response (as this is what we're aiming on achieving), I found this: http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div.

Just putting that there in case anyone else needs a solution. :)

Parsing PDF files (especially with tables) with PDFBox

ObjectExtractor oe = new ObjectExtractor(document);

SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm(); // Tabula algo.

Page page = oe.extract(1); // extract only the first page

for (int y = 0; y < sea.extract(page).size(); y++) {
  System.out.println("table: " + y);
  Table table = sea.extract(page).get(y);

  for (int i = 0; i < table.getColCount(); i++) {
    for (int x = 0; x < table.getRowCount(); x++) {
      System.out.println("col:" + i + "/lin:x" + x + " >>" + table.getCell(x, i).getText());
    }
  }
}

How can I debug a Perl script?

The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.

Brian Kernighan, "Unix for Beginners" (1979)

(And enhancing print statements with Data::Dumper)

How to add a char/int to an char array in C?

Suggest replacing this:

char str[1024];
char tmp = '.';

strcat(str, tmp);

with this:

char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()

strcat(str, tmp); // 

How to declare a local variable in Razor?

You can also use:

@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}

No need for a variable in the code

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

How to include layout inside layout?

Try this

<include
            android:id="@+id/OnlineOffline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            layout="@layout/YourLayoutName" />

Iterate Multi-Dimensional Array with Nested Foreach Statement

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

The output of this example is:

9 99 3 33 5 55

References


In Java, multidimensional arrays are array of arrays, so the following works:

    int[][] table = {
            { 1, 2, 3 },
            { 4, 5, 6 },
    };
    for (int[] row : table) {
        for (int el : row) {
            System.out.println(el);
        }
    }

JavaScript function to add X months to a date

Sometimes useful create date by one operator like in BIRT parameters

I made 1 month back with:

new Date(new Date().setMonth(new Date().getMonth()-1));   

How to manually update datatables table with new JSON data

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()

How to use Jackson to deserialise an array of objects

For Generic Implementation:

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}

compareTo with primitives -> Integer / int

Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :

Integer a = 3; 

About comparision there is Math.signum(double d).

compare= (int) Math.signum(a-b); 

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

make sure your user has attributes on its role. for example:

postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      |                                                | {}
 postgres  | Superuser, Create role, Create DB, Replication | {}

after performing the following command:

postgres=# ALTER ROLE flux WITH Superuser;
ALTER ROLE
postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      | Superuser                                      | {}
postgres  | Superuser, Create role, Create DB, Replication | {}

it fixed the problem.

see tutorial for roles and stuff here: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

How can I increase the JVM memory?

When calling java use the -Xmx Flag for example -Xmx512m for 512 megs for the heap size. You may also want to consider the -xms flag to start the heap larger if you are going to have it grow right from the start. The default size is 128megs.

compare differences between two tables in mysql

Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....

Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"

SELECT ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

So you need to add the extra "where in" clause:

WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)


Also:

For ease of reading if you want to indicate the table names you can use the following:

SELECT tbl, ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

How to convert integer to decimal in SQL Server query?

declare @xx int 
set     @xx = 3 
select @xx      
select @xx * 2  -- yields another integer  
select @xx/1    -- same
select @xx/1.0  --yields 6 decimal places 
select @xx/1.00 --       6 
select @xx * 1.0  --     1 decimal place - victory
select @xx * 1.00 --     2         places - hooray 

Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.

How can I reset or revert a file to a specific revision?

This worked for me:

git checkout <commit hash> file

Then commit the change:

git commit -a

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

In the examples below the client is the browser and the server is the webserver hosting the website.

Before you can understand these technologies, you have to understand classic HTTP web traffic first.

Regular HTTP:

  1. A client requests a webpage from a server.
  2. The server calculates the response
  3. The server sends the response to the client.

HTTP

Ajax Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).
  3. The server calculates each response and sends it back, just like normal HTTP traffic.

Ajax Polling

Ajax Long-Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.
  3. The server does not immediately respond with the requested information but waits until there's new information available.
  4. When there's new information available, the server responds with the new information.
  5. The client receives the new information and immediately sends another request to the server, re-starting the process.

Ajax Long-Polling

HTML5 Server Sent Events (SSE) / EventSource:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.
  3. The server sends an event to the client when there's new information available.

HTML5 SSE

HTML5 Websockets:

  1. A client requests a webpage from a server using regular http (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.
  3. The server and the client can now send each other messages when new data (on either side) is available.

    • Real-time traffic from the server to the client and from the client to the server
    • You'll want to use a server that has an event loop
    • With WebSockets it is possible to connect with a server from another domain.
    • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
    • If you want to read more, I found these very useful: (article), (article) (tutorial).

HTML5 WebSockets

Comet:

Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.


Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?

You can use PHP with WebSockets, check out Ratchet.

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

How to append text to an existing file in Java?

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {


    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}

Trying to SSH into an Amazon Ec2 instance - permission error

.400 protects it by making it read only and only for the owner.
You can find the answer from the ASW guide.

chmod 400 yourPrivateKey.pem

enter image description here

How to call a function from a string stored in a variable?

Solution: Use PHP7

Note: For a summarized version, see TL;DR at the end of the answer.

Old Methods

Update: One of the old methods explained here has been removed. Refer to other answers for explanation on other methods, it is not covered here. By the way, if this answer doesn't help you, you should return upgrading your stuff. PHP 5.6 support has ended in January 2019 (now even PHP 7.1 and 7.2 are not being supported). See supported versions for more information.

As others mentioned, in PHP5 (and also in newer versions like PHP7) we could use variables as function names, use call_user_func() and call_user_func_array() (which, personally, I hate those functions), etc.

New Methods

As of PHP7, there are new ways introduced:

Note: Everything inside <something> brackets means one or more expressions to form something, e.g. <function_name> means expressions forming a function name.

Dynamic Function Call: Function Name On-the-fly

We can use one or more expressions inside parentheses as the function name in just one go, in the form of:

(<function_name>)(arguments);

For example:

function something(): string
{
    return "something";
}

$bar = "some_thing";

(str_replace("_", "", $bar))(); // something

// Possible, too; but generally, not recommended, because makes your code more complicated
(str_replace("_", "", $bar))()(); 

Note: Although removing the parentheses around str_replace() is not an error, putting parentheses makes code more readable. However, you cannot do that sometimes, e.g. while using . operator. To be consistent, I recommend you to put the parentheses always.

Dynamic Method Call: Method Name On-the-fly

Just like dynamic function calls, we can do the same way with method calls, surrounded by curly braces instead of parentheses (for extra forms, navigate to TL;DR section):

$object->{<method_name>}(arguments);
$object::{<method_name>}(arguments);

See it in an example:

class Foo
{
    public function another(): string
    {
        return "something";
    }
}

$bar = "another thing";

(new Something())->{explode(" ", $bar)[0]}(); // something

Dynamic Method Call: The Array Syntax

A more elegant way added in PHP7 is the following:

[<object>, <method_name>](arguments);
[<class_name>, <method_name>](arguments); // Static calls only

As an example:

class Foo
{
    public function nonStaticCall()
    {
        echo "Non-static call";
    }
    public static function staticCall()
    {
        echo "Static call";
    }
}

$x = new X();

[$x, "non" . "StaticCall"](); // Non-static call
[$x, "static" . "Call"](); // Static call

Note: The benefit of using this method over the previous one is that, you don't care about the call type (i.e. whether it's static or not).

Note: If you care about performance (and micro-optimizations), don't use this method. As I tested, this method is really slower than other methods (more than 10 times).

Extra Example: Using Anonymous Classes

Making things a bit complicated, you could use a combination of anonymous classes and the features above:

$bar = "SomeThing";

echo (new class {
    public function something()
    {
        return 512;
    }
})->{strtolower($bar)}(); // 512

TL;DR (Conclusion)

Generally, in PHP7, using the following forms are all possible:

// Everything inside `<something>` brackets means one or more expressions
// to form something

// Dynamic function call
(<function_name>)(arguments)

// Dynamic method call on an object
$object->{<method_name>}(arguments)
$object::{<method_name>}(arguments)

// Dynamic method call on a dynamically-generated object
(<object>)->{<method_name>}(arguments)
(<object>)::{<method_name>}(arguments)

// Dynamic method call, statically
ClassName::{<method_name>}(arguments)
(<class_name>)::{<method_name>}(arguments)

// Dynamic method call, array-like (no different between static and non-static calls
[<object>, <method_name>](arguments)

// Dynamic method call, array-like, statically
[<class_name>, <method_name>](arguments)

Special thanks to this PHP talk.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

ComboBox.SelectedText doesn't give me the SelectedText

Try this:

String status = "The status of my combobox is " + comboBoxTest.text;

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To answer your question, yes it does: your synchronized method cannot be executed by more than one thread at a time.

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

What exactly is nullptr?

When you have a function that can receive pointers to more than one type, calling it with NULL is ambiguous. The way this is worked around now is very hacky by accepting an int and assuming it's NULL.

template <class T>
class ptr {
    T* p_;
    public:
        ptr(T* p) : p_(p) {}

        template <class U>
        ptr(U* u) : p_(dynamic_cast<T*>(u)) { }

        // Without this ptr<T> p(NULL) would be ambiguous
        ptr(int null) : p_(NULL)  { assert(null == NULL); }
};

In C++11 you would be able to overload on nullptr_t so that ptr<T> p(42); would be a compile-time error rather than a run-time assert.

ptr(std::nullptr_t) : p_(nullptr)  {  }

How to use ES6 Fat Arrow to .filter() an array of objects

return arrayname.filter((rec) => rec.age > 18)

Write this in the method and call it

How to change Vagrant 'default' machine name?

I found the multiple options confusing, so I decided to test all of them to see exactly what they do.

I'm using VirtualBox 4.2.16-r86992 and Vagrant 1.3.3.

I created a directory called nametest and ran

vagrant init precise64 http://files.vagrantup.com/precise64.box

to generate a default Vagrantfile. Then I opened the VirtualBox GUI so I could see what names the boxes I create would show up as.

  1. Default Vagrantfile

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
    end
    

    VirtualBox GUI Name: "nametest_default_1386347922"

    Comments: The name defaults to the format DIRECTORY_default_TIMESTAMP.

  2. Define VM

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
    end
    

    VirtualBox GUI Name: "nametest_foohost_1386347922"

    Comments: If you explicitly define a VM, the name used replaces the token 'default'. This is the name vagrant outputs on the console. Simplifying based on zook's (commenter) input

  3. Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.provider :virtualbox do |vb|
            vb.name = "foohost"
        end
    end
    

    VirtualBox GUI Name: "foohost"

    Comments: If you set the name attribute in a provider configuration block, that name will become the entire name displayed in the VirtualBox GUI.

    Combined Example: Define VM -and- Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end
    

    VirtualBox GUI Name: "barhost"

    Comments: If you use both methods at the same time, the value assigned to name in the provider configuration block wins. Simplifying based on zook's (commenter) input

  4. Set hostname (BONUS)

    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      config.vm.hostname = "buzbar"
    end
    

    Comments: This sets the hostname inside the VM. This would be the output of hostname command in the VM and also this is what's visible in the prompt like vagrant@<hostname>, here it will look like vagrant@buzbar

Final Code

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.hostname = "buzbar"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end

So there it is. You now know 3 different options you can set and the effects they have. I guess it's a matter of preference at this point? (I'm new to Vagrant, so I can't speak to best practices yet.)

HTML/JavaScript: Simple form validation on submit

The simplest validation is as follows:

_x000D_
_x000D_
<form name="ff1" method="post">
  <input type="email" name="email" id="fremail" placeholder="[email protected]" />
  <input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
  <input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
  <input type="submit" name="Submit" value="Continue" />
</form>
_x000D_
_x000D_
_x000D_

It uses HTML5 attributes (like as pattern).

JavaScript: none.

@Autowired - No qualifying bean of type found for dependency

You should autowire interface AbstractManager instead of class MailManager. If you have different implemetations of AbstractManager you can write @Component("mailService") and then @Autowired @Qualifier("mailService") combination to autowire specific class.

This is due to the fact that Spring creates and uses proxy objects based on the interfaces.

Catching "Maximum request length exceeded"

As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.

The default for the executionTimeout is 360 seconds or 6 minutes.

You can change the maxRequestLength and executionTimeout with the httpRuntime Element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" executionTimeout="1200" />
    </system.web>
</configuration>

EDIT:

If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.

UML diagram shapes missing on Visio 2013

If you don't see stencils creating new document with a template you may open the template directly. In my case they are located at 'C:\Program Files\Microsoft Office\Office15\Visio Content\1049\' Last foler name varies regarding locale, I guess. UML template is named 'DBUML_M.VSTX'

Double free or corruption after queue::push

Let's talk about copying objects in C++.

Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.

Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.

When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.

Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.

How do I fix it?

The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:

Test(const Test& other){
    myArray = new int[10];
    memcpy( myArray, other.myArray, 10 );
}

Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.

We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:

Test& operator= (const Test& other){
    if (this != &other) {
        memcpy( myArray, other.myArray, 10 );
    }
    return *this;
}

The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.

Is there any way I can define a variable in LaTeX?

This works for me: \newcommand{\variablename}{the text}

For eg: \newcommand\m{100}

So when you type " \m\ is my mark " in the source code,

the pdf output displays as :

100 is my mark

Argument list too long error for rm, cp, mv commands

I'm surprised there are no ulimit answers here. Every time I have this problem I end up here or here. I understand this solution has limitations but ulimit -s 65536 seems to often do the trick for me.

What is the standard way to add N seconds to datetime.time in Python?

You cannot simply add number to datetime because it's unclear what unit is used: seconds, hours, weeks...

There is timedelta class for manipulations with date and time. datetime minus datetime gives timedelta, datetime plus timedelta gives datetime, two datetime objects cannot be added although two timedelta can.

Create timedelta object with how many seconds you want to add and add it to datetime object:

>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)

There is same concept in C++: std::chrono::duration.

Printing one character at a time from a string, using the while loop

This will print each character in text

text = raw_input("Give some input:  ")
for i in range(0,len(text)):
   print(text[i])

How do I concatenate a boolean to a string in Python?

Using the so called f strings:

answer = True
myvar = f"the answer is {answer}"

Then if I do

print(myvar)

I will get:

the answer is True

I like f strings because one does not have to worry about the order in which the variables will appear in the printed text, which helps in case one has multiple variables to be printed as strings.

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

_x000D_
_x000D_
.social-media{_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Retrieve last 100 lines logs

I know this is very old, but, for whoever it may helps.

less +F my_log_file.log

that's just basic, with less you can do lot more powerful things. once you start seeing logs you can do search, go to line number, search for pattern, much more plus it is faster for large files.

its like vim for logs[totally my opinion]

original less's documentation : https://linux.die.net/man/1/less

less cheatsheet : https://gist.github.com/glnds/8862214

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I know this is an old post, but for anyone using Retrofit, this can be useful useful.

If you are using Retrofit + Jackson + Kotlin + Data classes, you need:

  1. add implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2' to your dependencies, so that Jackson can de-serialize into Data classes
  2. When building retrofit, pass the Kotlin Jackson Mapper, so that Retrofit uses the correct mapper, ex:
    val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()

    val retrofit = Retrofit.Builder()
          ...
          .addConverterFactory(JacksonConverterFactory.create(jsonMapper))
          .build()

Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.

Favicon not showing up in Google Chrome

I also experienced the same thing. I found out that my favicon.ico had not been processed as a legitimate shortcut icon. I understand that favicons must be scaled to 16x16 and follow the Microsoft Icon format.

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

I ran into this when checking on a null or empty string

if (x == NULL || x == '') {

changed it to

if (is.null(x) || x == '') {

References with text in LaTeX

Have a look to this wiki: LaTeX/Labels and Cross-referencing:

The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:

\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...

jQuery: set selected value of dropdown list?

UPDATED ANSWER:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

OLD ANSWER:

Use this instead:

$("#routetype option[value='quietest']").attr("selected", "selected");

Fiddle'd: http://jsfiddle.net/x3UyB/4/

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

Link to a section of a webpage

The fragment identifier (also known as: Fragment IDs, Anchor Identifiers, Named Anchors) introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.

<a href="http://www.someuri.com/page#fragment">Link to fragment identifier</a>

Syntax for URIs also allows an optional query part introduced by a question mark ?. In URIs with a query and a fragment the fragment follows the query.

<a href="http://www.someuri.com/page?query=1#fragment">Link to fragment with a query</a>

When a Web browser requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent (Web browser) processes the resource according to the document type and fragment value.

Named Anchors <a name="fragment"> are deprecated in XHTML 1.0, the ID attribute is the suggested replacement. <div id="fragment"></div>

AJAX jQuery refresh div every 5 seconds

Try using setInterval and include jquery library and just try removing unwrap()

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var timeout = setInterval(reloadChat, 5000);    
function reloadChat () {

     $('#links').load('test.php');
}
</script>

UPDATE

you are using a jquery old version so include the latest jquery version

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

How do I import other TypeScript files?

import {className} from 'filePath';

remember also. The class you are importing , that must be exported in the .ts file.

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

Removing character in list of strings

Here's a short one-liner using regular expressions:

print [re.compile(r"8").sub("", m) for m in mylist]

If we separate the regex operations and improve the namings:

pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res

How do I "break" out of an if statement?

Nested ifs:

if (condition)
{
    // half-massive amount of code here

    if (!breakOutCondition)
    {
        //half-massive amount of code here
    }
}

At the risk of being downvoted -- it's happened to me in the past -- I'll mention that another (unpopular) option would of course be the dreaded goto; a break statement is just a goto in disguise.

And finally, I'll echo the common sentiment that your design could probably be improved so that the massive if statement is not necessary, let alone breaking out of it. At least you should be able to extract a couple of methods, and use a return:

if (condition)
{
    ExtractedMethod1();

    if (breakOutCondition)
        return;

    ExtractedMethod2();
}

Difference between float and decimal data type

declare @float as float(10)
declare @Decimal as decimal(10)
declare @Inetger as int

set @float =10.7
set @Decimal =10.7
set @Inetger=@Decimal

print @Inetger

in float when set value to integer print 10 but in decimal 11

How to add a new column to a CSV file?

I used pandas and it worked well... While I was using it, I had to open a file and add some random columns to it and then save back to same file only.

This code adds multiple column entries, you may edit as much you need.

import pandas as pd

csv_input = pd.read_csv('testcase.csv')         #reading my csv file
csv_input['Phone1'] = csv_input['Name']         #this would also copy the cell value 
csv_input['Phone2'] = csv_input['Name']
csv_input['Phone3'] = csv_input['Name']
csv_input['Phone4'] = csv_input['Name']
csv_input['Phone5'] = csv_input['Name']
csv_input['Country'] = csv_input['Name']
csv_input['Website'] = csv_input['Name']
csv_input.to_csv('testcase.csv', index=False)   #this writes back to your file

If you want that cell value doesn't gets copy, so first of all create a empty Column in your csv file manually, like you named it as Hours then, Now for this you can add this line in above code,

csv_input['New Value'] = csv_input['Hours']

or simply we can, without adding the manual column, we can

csv_input['New Value'] = ''    #simple and easy

I Hope it helps.

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I ran into a similar problem today (but with mod_wsgi). It might be an Apache 2.2-to-2.4 problem. A comprehensive list of changes can be found here.

For me, it helped to add an additional <Directory>-entry for every path the error-log was complaining about and filling the section with Require all granted.

So in your case you could try

<Directory /usr/lib/cgi-bin/php5-fcgi>
    Require all granted
    Options FollowSymLinks
</Directory>

and I had to move my configuration file from folder conf.d to folder sites-enabled.

All in all, that did the trick for me, but I don't guarantee it works in your case as well.

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

Getting the WordPress Post ID of current post

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID