Programs & Examples On #Raima

how to show calendar on text box click in html

HTML Date Picker You can refer this.

:: (double colon) operator in Java 8

Usually, one would call the reduce method using Math.max(int, int) as follows:

reduce(new IntBinaryOperator() {
    int applyAsInt(int left, int right) {
        return Math.max(left, right);
    }
});

That requires a lot of syntax for just calling Math.max. That's where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way:

reduce((int left, int right) -> Math.max(left, right));

How does this work? The java compiler "detects", that you want to implement a method that accepts two ints and returns one int. This is equivalent to the formal parameters of the one and only method of interface IntBinaryOperator (the parameter of method reduce you want to call). So the compiler does the rest for you - it just assumes you want to implement IntBinaryOperator.

But as Math.max(int, int) itself fulfills the formal requirements of IntBinaryOperator, it can be used directly. Because Java 7 does not have any syntax that allows a method itself to be passed as an argument (you can only pass method results, but never method references), the :: syntax was introduced in Java 8 to reference methods:

reduce(Math::max);

Note that this will be interpreted by the compiler, not by the JVM at runtime! Although it produces different bytecodes for all three code snippets, they are semantically equal, so the last two can be considered to be short (and probably more efficient) versions of the IntBinaryOperator implementation above!

(See also Translation of Lambda Expressions)

How to create a localhost server to run an AngularJS project

cd <your project folder> (where your angularjs's deployable code is there)

sudo npm install serve -g

serve

You can hit your page at

localhost:3000 or IPaddress:3000

How do I increase modal width in Angular UI Bootstrap?

Use max-width on modal-dialog for angular 5

.mod-class .modal-dialog {
    max-width: 1000px;
}

and use windowClass as others recommended, TS eg:

this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
        (result) => {
            // this.closeResult = `Closed with: ${result}`;
         }, (reason) => {
            // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});

Also, I had to put the css code in global styles > styles.css.

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

calling parent class method from child class object in java

First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method. Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.

Bootstrap dropdown menu not working (not dropping down when clicked)

Just add both these files after opening of body tag. Keep in mind 'Only after Body tag' any where after body tag. If you add below mentioned files inside body tag then your problems would still be unresolved.

So paste them after or before close of body tag... This works 100%. I've tested and got it working!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

jquery beforeunload when closing (not leaving) the page?

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?

Hiding axis text in matplotlib plots

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

Module not found: Error: Can't resolve 'core-js/es6'

If you use @babel/preset-env and useBuiltIns, then you just have to add corejs: 3 beside the useBuiltIns option, to specify which version to use, default is corejs: 2.

presets: [
  [
    "@babel/preset-env", {
      "useBuiltIns": "usage",
      "corejs": 3
    }
  ]
],

For further details see: https://github.com/zloirock/core-js/blob/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md#babelpreset-env

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

Pyspark: display a spark data frame in a table format

Yes: call the toPandas method on your dataframe and you'll get an actual pandas dataframe !

Use ssh from Windows command prompt

Cygwin can give you this functionality.

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

How to show an alert box in PHP?

change your output from

 echo '<script language="javascript>';

to

 echo '<script type="text/javascript">';

you forgot double quotes... and use the type tag

Where are environment variables stored in the Windows Registry?

I always had problems with that, and I made a getx.bat script:

:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment

@SETLOCAL EnableDelayedExpansion
@echo OFF

@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S

@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@  set l_a=%%A
@    if NOT "!l_a!"=="!l_a:    =!" set l_line=!l_a!
)

:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line:    =    %

@set getxvalue=

@FOR /F "tokens=3* delims=  " %%A IN ("%l_line%") DO (
@    set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL

:: We already used tab as a delimiter
@FOR /F "delims=    " %%A IN (getxfile.tmp.txt) DO (
    @set getxvalue=%%A
)
@del getxfile.tmp.txt

@echo ON

SwiftUI - How do I change the background color of a View?

Use Below Code for Navigation Bar Color Customization

struct ContentView: View {

@State var msg = "Hello SwiftUI"
init() {
    UINavigationBar.appearance().backgroundColor = .systemPink

     UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.white,
               .font : UIFont(name:"Helvetica Neue", size: 40)!]

    // 3.
    UINavigationBar.appearance().titleTextAttributes = [
        .font : UIFont(name: "HelveticaNeue-Thin", size: 20)!]

}
var body: some View {
    NavigationView {
    Text(msg)
        .navigationBarTitle(Text("NAVIGATION BAR"))       
    }
    }
}

enter image description here

Create zip file and ignore directory structure

Use the -j option:

   -j     Store  just the name of a saved file (junk the path), and do not
          store directory names. By default, zip will store the full  path
          (relative to the current path).

Highest Salary in each department

Use following command;

SELECT  A.*
    FROM    @EmpDetails A
            INNER JOIN ( SELECT DeptID ,
                                MAX(salary) AS salary
                         FROM   @EmpDetails
                         GROUP BY DeptID
                       ) B ON A.DeptID = B.DeptID
                              AND A.salary = B.salary
    ORDER BY A.DeptID

TreeMap sort by value

Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
        new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = e1.getValue().compareTo(e2.getValue());
                if (e1.getKey().equals(e2.getKey())) {
                    return res; // Code will now handle equality properly
                } else {
                    return res != 0 ? res : 1; // While still adding all entries
                }
            }
        }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}

"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)

Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.

Using sed to split a string with a delimiter

Using \n in sed is non-portable. The portable way to do what you want with sed is:

sed 's/:/\
/g' ~/Desktop/myfile.txt

but in reality this isn't a job for sed anyway, it's the job tr was created to do:

tr ':' '
' < ~/Desktop/myfile.txt

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Although the accepted answer is correct, I'd prefer creating a new user and then using that user to access the database.

create user nodeuser@localhost identified by 'nodeuser@1234';
grant all privileges on node.* to nodeuser@localhost;
ALTER USER 'nodeuser'@localhost IDENTIFIED WITH mysql_native_password BY 'nodeuser@1234';

How to list running screen sessions?

 For windows system

 Open putty 
 then login in server

If you want to see screen in Console then you have to write command

 Screen -ls

if you have to access the screen then you have to use below command

 screen -x screen id

Write PWD in command line to check at which folder you are currently

.keyCode vs. .which

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

Copy map values to vector in STL

One way is to use functor:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}

Appropriate datatype for holding percent values?

  • Hold as a decimal.
  • Add check constraints if you want to limit the range (e.g. between 0 to 100%; in some cases there may be valid reasons to go beyond 100% or potentially even into the negatives).
  • Treat value 1 as 100%, 0.5 as 50%, etc. This will allow any math operations to function as expected (i.e. as opposed to using value 100 as 100%).
  • Amend precision and scale as required (these are the two values in brackets columnName decimal(precision, scale). Precision says the total number of digits that can be held in the number, scale says how many of those are after the decimal place, so decimal(3,2) is a number which can be represented as #.##; decimal(5,3) would be ##.###.
  • decimal and numeric are essentially the same thing. However decimal is ANSI compliant, so always use that unless told otherwise (e.g. by your company's coding standards).

Example Scenarios

  • For your case (0.00% to 100.00%) you'd want decimal(5,4).
  • For the most common case (0% to 100%) you'd want decimal(3,2).
  • In both of the above, the check constraints would be the same

Example:

if object_id('Demo') is null
create table Demo
    (
        Id bigint not null identity(1,1) constraint pk_Demo primary key
        , Name nvarchar(256) not null constraint uk_Demo unique 
        , SomePercentValue decimal(3,2) constraint chk_Demo_SomePercentValue check (SomePercentValue between 0 and 1)
        , SomePrecisionPercentValue decimal(5,2) constraint chk_Demo_SomePrecisionPercentValue check (SomePrecisionPercentValue between 0 and 1)
    )

Further Reading:

jQuery ID starts with

try:

$("td[id^=" + value + "]")

How do I rename a repository on GitHub?

This answer is now obsolete! GitHub will forward to new locations now. See this answer for details.


The reason this warning is there is because #1 can't be made manually.

If you are the only person working on and linking to the repository, then you are fine with changing the remote in your local repo and in your webpages.

However, the reason to have a public repository on github in the first place is that you can have others cloning your repository and linking to your github project page.


The old url github.com/<username>/<repository> is owned by github. When they don't setup any redirects to the new url, nobody can. So things will break for everybody except the persons you are telling.

How big of a problem that is, is up to you though. If you have an official project page on a different server, then the github url might not be much of a problem. If you advertised your project with the github url in mailing lists and directories, then you probably should not change the repo name.


An alternative to changing the repo name is to create a new repository and leave notes in the old one (also as commits in the repo) about how to reach your new repo.

If you wan't your new repo to be listed as a fork of your old repo you need to create a new github account. You can add your other account as a collaborator for both repositories.

How to Get JSON Array Within JSON Object?

Solved, use array list of string to get name from Ingredients. Use below code:

JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();

//loop to get all json objects from data json array
for(int i=0; i<length; i++){
    JSONObject jObj = ja_data.getJSONObject(i);
    Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
    // getting inner array Ingredients
    JSONArray ja = jObj.getJSONArray("Ingredients");
    int len = ja.length();
    ArrayList<String> Ingredients_names = new ArrayList<>();
    for(int j=0; j<len; j++){
        JSONObject json = ja.getJSONObject(j);
        Ingredients_names.add(json.getString("name"));
    }
}

Call web service in excel

In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.

Sub Demo()
    Dim XDoc As MSXML2.DOMDocument
    Dim xEmpDetails As MSXML2.IXMLDOMNode
    Dim xParent As MSXML2.IXMLDOMNode
    Dim xChild As MSXML2.IXMLDOMNode
    Dim query As String
    Dim Col, Row As Integer
    Dim objWS As New clsws_GlobalWeather

    Set XDoc = New MSXML2.DOMDocument
    XDoc.async = False
    XDoc.validateOnParse = False
    query = objWS.wsm_GetCitiesByCountry("india")

    If Not XDoc.LoadXML(query) Then  'strXML is the string with XML'
        Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
    End If
    XDoc.LoadXML (query)

    Set xEmpDetails = XDoc.DocumentElement
    Set xParent = xEmpDetails.FirstChild
    Worksheets("Sheet3").Cells(1, 1).Value = "Country"
    Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
    Worksheets("Sheet3").Cells(1, 2).Value = "City"
    Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
    Row = 2
    Col = 1
    For Each xParent In xEmpDetails.ChildNodes
        For Each xChild In xParent.ChildNodes
            Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
            Col = Col + 1
        Next xChild
        Row = Row + 1
        Col = 1
    Next xParent
End Sub

Webdriver findElements By xpath

Instead of

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

Why is my CSS bundling not working with a bin deployed MVC4 app?

With Visual Studio 2015 I found the problem was caused by referencing the .min version of a javascript file in the BundleConfig when debug=true is set in the web.config.

For example, with jquery specifying the following in BundleConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.min.js"));

resulted in the jquery not loading correctly at all when debug=true was set in the web.config.

Referencing the un-minified version:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

corrects the problem.

Setting debug=false also corrects the problem, but of course that is not exactly helpful.

It is also worth noting that while some minified javascript files loaded correctly and others did not. I ended up removing all minified javascript files in favor of VS handling minification for me.

find a minimum value in an array of floats

You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed

def get_min_value(self, table):
    min_values = []
    for i in range(0, len(table)):
        min_value = min(table[i])
        min_values.append(min_value)

    return min(min_values)

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

How to change default language for SQL Server?

If you want to change MSSQL server language, you can use the following QUERY:

EXEC sp_configure 'default language', 'British English';

node.js, socket.io with SSL

On the same note, if your server supports both http and https you can connect using:

var socket = io.connect('//localhost');

to auto detect the browser scheme and connect using http/https accordingly. when in https, the transport will be secured by default, as connecting using

var socket = io.connect('https://localhost');

will use secure web sockets - wss:// (the {secure: true} is redundant).

for more information on how to serve both http and https easily using the same node server check out this answer.

How to use executables from a package installed locally in node_modules?

Same @regular 's accepted solution, but Fish shell flavour

if not contains (npm bin) $PATH
    set PATH (npm bin) $PATH
end

Delimiters in MySQL

When you create a stored routine that has a BEGIN...END block, statements within the block are terminated by semicolon (;). But the CREATE PROCEDURE statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE, or terminates one of the statements within the body of the procedure.

The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE statement.

How to check user is "logged in"?

I managed to find the correct one. It is below.

bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

EDIT

The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.

bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

Faced the same issue in Netbeans 8.0.2. Clean and Build Project solved this problem.

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Since cP/WHM took away the ability to modify User privileges as root in PHPMyAdmin, you have to use the command line to:

mysql>  GRANT FILE ON *.* TO 'user'@'localhost';

Step 2 is to allow that user to dump a file in a specific folder. There are a few ways to do this but I ended up putting a folder in :

/home/user/tmp/db

and

chown mysql:mysql /home/user/tmp/db

That allows the mysql user to write the file. As previous posters have said, you can use the MySQL temp folder too, I don't suppose it really matters but you definitely don't want to make it 0777 permission (world-writeable) unless you want the world to see your data. There is a potential problem if you want to rinse-repeat the process as INTO OUTFILE won't work if the file exists. If your files are owned by a different user then just trying to unlink($file) won't work. If you're like me (paranoid about 0777) then you can set your target directory using:

chmod($dir,0777)

just prior to doing the SQL command, then

chmod($dir,0755)

immediately after, followed by unlink(file) to delete the file. This keeps it all running under your web user and no need to invoke the mysql user.

Datatables on-the-fly resizing

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

Facebook Open Graph not clearing cache

  1. Visit the FB page https://developers.facebook.com/tools/debug/og/object/
  2. Enter your domain.
  3. Click the button "Fetch new scrape information"
  4. Done

Javascript: set label text

you are doing several things wrong. The explanation follows the corrected code:

<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>

Note the quotes around the id.

function checkLength(object, maxlength, label) {
    charsleft = (maxlength - object.value.length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        object.value = object.value.substring(0, maxlength-1);
    }

    // set the value of charsleft into the label
    document.getElementById(label).innerHTML = charsleft;
}

First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.

Let me know how that works out for you

EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:

var charsleft = ....

When to use an interface instead of an abstract class and vice versa?

When to do what is a very simple thing if you have the concept clear in your mind.

Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

I hope I am clear.

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

Benefits of using the conditional ?: (ternary) operator

One thing to recognize when using the ternary operator that it is an expression not a statement.

In functional languages like scheme the distinction doesn't exists:

(if (> a b) a b)

Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"

In functional languages it is.

When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

My requirement is to display 10 digit phone number in the jsp. So here's the setup for me.
MySQL: numeric(10)

Java Side:

@NumberFormat(pattern = "#")  
private long mobileNumber;

and it worked!

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

jQuery add image inside of div tag

Have you tried the following:

$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

C# - Substring: index and length must refer to a location within the string

How about something like this :

string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension =  Path.GetExtension(path_Query);

path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

What is the equivalent of "!=" in Excel VBA?

Try to use <> instead of !=.

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

Reliable method to get machine's MAC address in C#

Cleaner solution

var macAddr = 
    (
        from nic in NetworkInterface.GetAllNetworkInterfaces()
        where nic.OperationalStatus == OperationalStatus.Up
        select nic.GetPhysicalAddress().ToString()
    ).FirstOrDefault();

Or:

String firstMacAddress = NetworkInterface
    .GetAllNetworkInterfaces()
    .Where( nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback )
    .Select( nic => nic.GetPhysicalAddress().ToString() )
    .FirstOrDefault();

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Using scp to copy a file to Amazon EC2 instance?

The process of using SCP to copy files from a local machine to an AWS EC2 Linux instance is covered step-by-step (including the points mentioned below) in this video.

To correct this particular issue with using SCP:

  1. You need to specify the correct Linux user. From Amazon:

    • For Amazon Linux, the user name is ec2-user.
    • For RHEL, the user name is ec2-user or root.
    • For Ubuntu, the user name is ubuntu or root.
    • For Centos, the user name is centos.
    • For Fedora, the user name is ec2-user.
    • For SUSE, the user name is ec2-user or root.
    • Otherwise, if ec2-user and root don't work, check with your AMI provider.
  2. Your private key must not be publicly visible. Run the following command so that only the root user can read the file.

    chmod 400 /path/to/yourKeyFile.pem
    

Compile error: package javax.servlet does not exist

place jakarta and delete javax

if you download servlet.api.jar :

NOTICE : this answer every time is not correct ( can be javax in JEE )

Correct

jakarta.servlet.*;

Incorrect

javax.servlet.*;

else :

place jar files into JAVA_HOME/jre/lib/ext

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Beyond removing .m2/repository, remove application from server, run server (without applications), stop it and add application again. Now it is supposed to work. For some reason just cleaning up server folders from interface doesn't have the same effect.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

How about something like this?

<div id="leftContainer">
  <span>Company Name</span>
  <br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
  <span>Contact Name</span>
  <br><input type="text" value="Timothy Patten">
</div>

Then, you can align the 2 divs by floating them left and right:-

#leftContainer {
   float:left;
}

#rightContainer {
   float:right;
}

how to open a jar file in Eclipse

The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.

How do I drop a function if it already exists?

If you want to use the SQL ISO standard INFORMATION_SCHEMA and not the SQL Server-specific sysobjects, you can do this:

IF EXISTS (
    SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = N'FunctionName'
)
   DROP FUNCTION [dbo].[FunctionName]
GO

Add/remove HTML inside div using JavaScript

You can do something like this.

function addRow() {
  const div = document.createElement('div');

  div.className = 'row';

  div.innerHTML = `
    <input type="text" name="name" value="" />
    <input type="text" name="value" value="" />
    <label> 
      <input type="checkbox" name="check" value="1" /> Checked? 
    </label>
    <input type="button" value="-" onclick="removeRow(this)" />
  `;

  document.getElementById('content').appendChild(div);
}

function removeRow(input) {
  document.getElementById('content').removeChild(input.parentNode);
}

SQL How to replace values of select return?

Replace the value in select statement itself...

(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)

Fully custom validation error message with Rails

Now, the accepted way to set the humanized names and custom error messages is to use locales.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"

Now the humanized name and the presence validation message for the "email" attribute have been changed.

Validation messages can be set for a specific model+attribute, model, attribute, or globally.

Why is synchronized block better than synchronized method?

It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.

Synchronized Methods

An entire method can be marked as synchronized resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.

Steps A thread access the synchronized method. It implicitly acquires the lock and execute the code. If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released.

Synchronized Blocks

To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste.

More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.

How to display a Yes/No dialog box on Android?

In Kotlin:

AlertDialog.Builder(this)
    .setTitle(R.string.question_title)
    .setMessage(R.string.question_message)
    .setPositiveButton(android.R.string.yes) { _, _ -> yesClicked() }
    .setNegativeButton(android.R.string.no) { _, _ -> noClicked() }
    .show()

How do I use the new computeIfAbsent function?

Suppose you have the following code:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    public static void main(String[] s) {
        Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
    }
    static boolean f(String s) {
        System.out.println("creating a value for \""+s+'"');
        return s.isEmpty();
    }
}

Then you will see the message creating a value for "snoop" exactly once as on the second invocation of computeIfAbsent there is already a value for that key. The k in the lambda expression k -> f(k) is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.

Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty()); to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty); This delegation does not need any parameters to be written.

To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key)); (it doesn’t matter whether you name the parameter k or key). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut); if tryToLetOut is static or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut); if tryToLetOut is an instance method.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

For a CSS-only (and icon-free) solution using Bootstrap 3 I had to do a bit of fiddling based on Martin Wickman's answer above.

I didn't use the accordion-* notation because it's done with panels in BS3.

Also, I had to include in the initial HTML aria-expanded="true" on the item that's open at page load.

Here is the CSS I used.

.accordion-toggle:hover { text-decoration: none; }
.accordion-toggle:hover span, .accordion-toggle:hover strong { text-decoration: underline; }
.accordion-toggle:before { font-size: 25px; }
.accordion-toggle[data-toggle="collapse"]:before { content: "+"; margin-right: 0px; }
.accordion-toggle[aria-expanded="true"]:before { content: "-"; margin-right: 0px; }

Here is my sanitized HTML:

<div id="acc1">    
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" aria-expanded="true" data-parent="#acc1" href="#acc1-1">Title 1
                    </a>
            </span>
        </div>
        <div id=“acc1-1” class="panel-collapse collapse in">
            <div class="panel-body">
                Text 1
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc1” href=“#acc1-2”>Title 2
                    </a>
            </span>
        </div>
        <div id=“acc1-2” class="panel-collapse collapse">
            <div class="panel-body">
                Text 2                  
            </div>
        </div>
    </div>
</div>

Explain why constructor inject is better than other options

With examples? Here's a simple one:

public class TwoInjectionStyles {
    private Foo foo;

    // Constructor injection
    public TwoInjectionStyles(Foo f) {
        this.foo = f;
    }

    // Setting injection
    public void setFoo(Foo f) { this.foo = f; }
}

Personally, I prefer constructor injection when I can.

In both cases, the bean factory instantiates the TwoInjectionStyles and Foo instances and gives the former its Foo dependency.

Show/Hide Div on Scroll

Try this code

$('window').scrollDown(function(){$(#div).hide()});

$('window').scrollUp(function(){ $(#div).show() });

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

http://www.website.com/CSS/Style.css

How do I reference a cell within excel named range?

I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read. I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row()) but I found it a bit too long for my tastes.

However, in this particular case, I found that using Sales alone works just as well - Excel (2010 here) just gets the corresponding row automatically.

It appears to work with other ranges too; for example let's say I have values in A2:A11 which I name Sales, I can just use =Sales*0.21 in B2:11 and it will use the same row value, giving out ten different results.


I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)

erlative named range

How to handle windows file upload using Selenium WebDriver?

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

Get the position of a spinner in Android

    final int[] positions=new int[2]; 
    Spinner sp=findViewByID(R.id.spinner);

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            Toast.makeText( arg2....);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

This view is not constrained

Alright so I know this answer is old, but I found out how to do this for version 3.1.4. So for me this error occurs whenever I put in a new item into the hierarchy, so I knew I needed a solution. After tinkering around for a little bit I found how to do it by following these steps:

  1. Right click the object and go to Center.

Step 1

  1. Then select Horizontally.

Step 2

  1. Repeat those steps, except click Vertically instead of Horizontally.

Provided that that method still works, after step two you should see squiggly lines going horizontally across where the item is, and after step three, both horizontally and vertically. After step three, the error will go away!

How to select the last record from MySQL table using SQL syntax

SELECT MAX("field name") AS ("primary key") FROM ("table name")

example:

SELECT MAX(brand) AS brandid FROM brand_tbl

Where does one get the "sys/socket.h" header/source file?

Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).

This library files should be under cygwin\usr\include

Regards.

Python: finding an element in a list

Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):

el = [x for x in mylist if x.attr == "foo"][0]

Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.

What exactly is a Maven Snapshot and why do we need it?

As the name suggests, snapshot refers to a state of project and its dependencies at that moment of time. Whenever maven finds a newer SNAPSHOT of the project, it downloads and replaces the older .jar file of the project in the local repository.

Snapshot versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a snapshot release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build.

How to display the value of the bar on each bar with pyplot.barh()?

I was trying to do this with stacked plot bars. The code that worked for me was.

# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))

# Loop to add on each bar a tag in position
for rect in ax.patches:
    height = rect.get_height()
    ypos = rect.get_y() + height/2
    ax.text(rect.get_x() + rect.get_width()/2., ypos,
            '%d' % int(height), ha='center', va='bottom')

How do I change the formatting of numbers on an axis with ggplot?

I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:

 ggplot + scale_x_continuous(labels = human_gbp)

which give you human readable numbers for x or y axes (or any number in general really).

You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.

How to enable bulk permission in SQL Server

SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:

icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

If you use multiple input in on field, follow: For example:

class AddUser extends React.Component {
   constructor(props){
     super(props);

     this.state = {
       fields: { UserName: '', Password: '' }
     };
   }

   onChangeField = event => {
    let name = event.target.name;
    let value = event.target.value;
    this.setState(prevState => {
        prevState.fields[name] =  value;
        return {
           fields: prevState.fields
        };
    });
  };

  render() { 
     const { UserName, Password } = this.state.fields;
     return (
         <form>
             <div>
                 <label htmlFor="UserName">UserName</label>
                 <input type="text" 
                        id='UserName' 
                        name='UserName'
                        value={UserName}
                        onChange={this.onChangeField}/>
              </div>
              <div>
                  <label htmlFor="Password">Password</label>
                  <input type="password" 
                         id='Password' 
                         name='Password'
                         value={Password}
                         onChange={this.onChangeField}/>
              </div>
         </form>
     ); 
  }
}

Search your problem at:

onChangeField = event => {
    let name = event.target.name;
    let value = event.target.value;
    this.setState(prevState => {
        prevState.fields[name] =  value;
        return {
            fields: prevState.fields
        };
    });
};

Why is it OK to return a 'vector' from a function?

To well understand the behaviour, you can run this code:

#include <iostream>

class MyClass
{
  public:
    MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
    ~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
    MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
    MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};

MyClass my_function()
{
  std::cout << "run my_function()" << std::endl;
  MyClass a;
  std::cout << "my_function is going to return a..." << std::endl;
  return a;
}

int main(int argc, char** argv)
{
  MyClass b = my_function();

  MyClass c;
  c = my_function();

  return 0;
}

The output is the following:

run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()

Note that this example was provided in C++03 context, it could be improved for C++ >= 11

Convert HashBytes to VarChar

SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', 'Hello World'),2)

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

You have no shell at /bin/sh? Have you tried docker run -it pensu/busybox /usr/bin/sh ?

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

What's the source of Error: getaddrinfo EAI_AGAIN?

If you get this error from within a docker container, e.g. when running npm install inside of an alpine container, the cause could be that the network changed since the container was started.

To solve this, just stop and restart the container

docker-compose down
docker-compose up

Source: https://github.com/moby/moby/issues/32106#issuecomment-578725551

How to sort Map values by key in Java?

We can also sort the key by using Arrays.sort method.

Map<String, String> map = new HashMap<String, String>();
Object[] objArr = new Object[map.size()];
for (int i = 0; i < map.size(); i++) {
objArr[i] = map.get(i);
}
Arrays.sort(objArr);
for (Object str : objArr) {
System.out.println(str);
}

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I tried all possible options but result is zero. Finally i found correct solution which is helpful for me. Just go to disable Instant Run Go to File -> Settings -> Build,Execution, Deployment -> Instant Run -> Uncheck the checkbox for instant run. Run your app once and this apk file work properly..

Bootstrap - dropdown menu not working?

This is a Rails specific answer, but I had this same problem with Bootstrap dropdown menus in my Rails app. What fixed it was adding this to app/assets/javascripts/application.js:

//= require bootstrap

Hope that helps someone.

How to Correctly handle Weak Self in Swift Blocks with Arguments

EDIT: Reference to an updated solution by LightMan

See LightMan's solution. Until now I was using:

input.action = { [weak self] value in
    guard let this = self else { return }
    this.someCall(value) // 'this' isn't nil
}

Or:

input.action = { [weak self] value in
    self?.someCall(value) // call is done if self isn't nil
}

Usually you don't need to specify the parameter type if it's inferred.

You can omit the parameter altogether if there is none or if you refer to it as $0 in the closure:

input.action = { [weak self] in
    self?.someCall($0) // call is done if self isn't nil
}

Just for completeness; if you're passing the closure to a function and the parameter is not @escaping, you don't need a weak self:

[1,2,3,4,5].forEach { self.someCall($0) }

How to change the default collation of a table?

To change the default character set and collation of a table including those of existing columns (note the convert to clause):

alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;

Edited the answer, thanks to the prompting of some comments:

Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41

and

That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

How to check if object has any properties in JavaScript?

for (var hasProperties in ad) break;
if (hasProperties)
    ... // ad has properties

If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

var hasProperties = false;
for (var x in ad) {
    if (ad.hasOwnProperty(x)) {
        hasProperties = true;
        break;
    }
}
if (hasProperties)
    ... // ad has properties

1030 Got error 28 from storage engine

My /var/log/apache2 folder was 35g and some logs in /var/log totaled to be the other 5g of my 40g hard drive. I cleared out all the *.gz logs and after making sure the other logs werent going to do bad things if I messed with them, i just cleared them too.

echo "clear" > access.log

etc.

find if an integer exists in a list of integers

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7}); // 1

List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2

var i = 5;
var x = ints.Contains(i);   // return true or false

How do I make a redirect in PHP?

Yes, it's possible to use PHP. We will redirect to another page.

Try following code:

<?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.php");
?>

How to add a touch event to a UIView?

In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:

//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap = 
  [[UITapGestureRecognizer alloc] initWithTarget:self 
                                          action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
  CGPoint location = [recognizer locationInView:[recognizer.view superview]];

  //Do stuff here...
}

There are a bunch of built in gestures as well. Check out the docs for iOS event handling and UIGestureRecognizer. I also have a bunch of sample code up on github that might help.

Bootstrap 3 - How to load content in modal body via AJAX?

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.ajax('your/url.html');
    

_x000D_
_x000D_
$(document).ready(function () {/* activate scroll spy menu */_x000D_
_x000D_
    var iconPrefix = '.glyphicon-';_x000D_
_x000D_
_x000D_
    $(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
    $(iconPrefix + 'comment').click(alertDemo);_x000D_
    $(iconPrefix + 'ok').click(confirmDemo);_x000D_
    $(iconPrefix + 'pencil').click(promptDemo);_x000D_
    $(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
    ///////////////////* Implementation *///////////////////_x000D_
_x000D_
    // Demos_x000D_
    function ajaxDemo() {_x000D_
        var title = 'Ajax modal';_x000D_
        var params = {_x000D_
            buttons: [_x000D_
               { text: 'Close', close: true, style: 'danger' },_x000D_
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
            ],_x000D_
            size: eModal.size.lg,_x000D_
            title: title,_x000D_
            url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
        };_x000D_
_x000D_
        return eModal_x000D_
            .ajax(params)_x000D_
            .then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function alertDemo() {_x000D_
        var title = 'Alert modal';_x000D_
        return eModal_x000D_
            .alert('You welcome! Want clean code ?', title)_x000D_
            .then(function () { alert('Alert modal is visible.', title); });_x000D_
    }_x000D_
_x000D_
    function confirmDemo() {_x000D_
        var title = 'Confirm modal callback feedback';_x000D_
        return eModal_x000D_
            .confirm('It is simple enough?', 'Confirm modal')_x000D_
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
    }_x000D_
_x000D_
    function iframeDemo() {_x000D_
        var title = 'Insiders';_x000D_
        return eModal_x000D_
            .iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)_x000D_
            .then(function () { alert('iFrame loaded!!!!', title) });_x000D_
    }_x000D_
_x000D_
    function promptDemo() {_x000D_
        var title = 'Prompt modal callback feedback';_x000D_
        return eModal_x000D_
            .prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })_x000D_
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })_x000D_
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
    }_x000D_
_x000D_
    //#endregion_x000D_
});
_x000D_
.fa{_x000D_
  cursor:pointer;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >_x000D_
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<div class="row" itemprop="about">_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Ajax</h3>_x000D_
    <p>You must get the message from a remote server? No problem!</p>_x000D_
    <i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Alert</h3>_x000D_
    <p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
    <i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10 text-center">_x000D_
    <h3>Confirm</h3>_x000D_
    <p>Get an okay from user, has never been so simple and clean!</p>_x000D_
    <i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>Prompt</h3>_x000D_
    <p>Do you have a question for the user? We take care of it...</p>_x000D_
    <i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-2 text-center">_x000D_
  <div class="row">_x000D_
   <div class="col-sm-10  text-center">_x000D_
    <h3>iFrame</h3>_x000D_
    <p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
    <i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <div class="col-sm-1 text-center"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Very Simple, Very Smooth, JavaScript Marquee

I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };

    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();
};
})(jQuery);

usage:

for start: $('#Text1').marquee()

pause: $('#Text1').marquee({ pause: true })

resume: $('#Text1').marquee({ pause: false })

XSS filtering function in PHP

I found a solution for my problem with the posts with german umlaut. To provide from totally cleaning (killing) the posts, i encode the incoming data:

    *$data = utf8_encode($data);
    ... function ...*

And at last i decode the output to get correct signs:

    *$data = utf8_decode($data);*

Now the post go through the filter function and i get a correct result...

An implementation of the fast Fourier transform (FFT) in C#

I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.

I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.

/**
 * Performs an in-place complex FFT.
 *
 * Released under the MIT License
 *
 * Copyright (c) 2010 Gerald T. Beauregard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
public class FFT2
{
    // Element for linked list in which we store the
    // input/output data. We use a linked list because
    // for sequential access it's faster than array index.
    class FFTElement
    {
        public double re = 0.0;     // Real component
        public double im = 0.0;     // Imaginary component
        public FFTElement next;     // Next element in linked list
        public uint revTgt;         // Target position post bit-reversal
    }

    private uint m_logN = 0;        // log2 of FFT size
    private uint m_N = 0;           // FFT size
    private FFTElement[] m_X;       // Vector of linked list elements

    /**
     *
     */
    public FFT2()
    {
    }

    /**
     * Initialize class to perform FFT of specified size.
     *
     * @param   logN    Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
     */
    public void init(
        uint logN )
    {
        m_logN = logN;
        m_N = (uint)(1 << (int)m_logN);

        // Allocate elements for linked list of complex numbers.
        m_X = new FFTElement[m_N];
        for (uint k = 0; k < m_N; k++)
            m_X[k] = new FFTElement();

        // Set up "next" pointers.
        for (uint k = 0; k < m_N-1; k++)
            m_X[k].next = m_X[k+1];

        // Specify target for bit reversal re-ordering.
        for (uint k = 0; k < m_N; k++ )
            m_X[k].revTgt = BitReverse(k,logN);
    }

    /**
     * Performs in-place complex FFT.
     *
     * @param   xRe     Real part of input/output
     * @param   xIm     Imaginary part of input/output
     * @param   inverse If true, do an inverse FFT
     */
    public void run(
        double[] xRe,
        double[] xIm,
        bool inverse = false )
    {
        uint numFlies = m_N >> 1;   // Number of butterflies per sub-FFT
        uint span = m_N >> 1;       // Width of the butterfly
        uint spacing = m_N;         // Distance between start of sub-FFTs
        uint wIndexStep = 1;        // Increment for twiddle table index

        // Copy data into linked complex number objects
        // If it's an IFFT, we divide by N while we're at it
        FFTElement x = m_X[0];
        uint k = 0;
        double scale = inverse ? 1.0/m_N : 1.0;
        while (x != null)
        {
            x.re = scale*xRe[k];
            x.im = scale*xIm[k];
            x = x.next;
            k++;
        }

        // For each stage of the FFT
        for (uint stage = 0; stage < m_logN; stage++)
        {
            // Compute a multiplier factor for the "twiddle factors".
            // The twiddle factors are complex unit vectors spaced at
            // regular angular intervals. The angle by which the twiddle
            // factor advances depends on the FFT stage. In many FFT
            // implementations the twiddle factors are cached, but because
            // array lookup is relatively slow in C#, it's just
            // as fast to compute them on the fly.
            double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
            if (inverse == false)
                wAngleInc *= -1;
            double wMulRe = Math.Cos(wAngleInc);
            double wMulIm = Math.Sin(wAngleInc);

            for (uint start = 0; start < m_N; start += spacing)
            {
                FFTElement xTop = m_X[start];
                FFTElement xBot = m_X[start+span];

                double wRe = 1.0;
                double wIm = 0.0;

                // For each butterfly in this stage
                for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
                {
                    // Get the top & bottom values
                    double xTopRe = xTop.re;
                    double xTopIm = xTop.im;
                    double xBotRe = xBot.re;
                    double xBotIm = xBot.im;

                    // Top branch of butterfly has addition
                    xTop.re = xTopRe + xBotRe;
                    xTop.im = xTopIm + xBotIm;

                    // Bottom branch of butterly has subtraction,
                    // followed by multiplication by twiddle factor
                    xBotRe = xTopRe - xBotRe;
                    xBotIm = xTopIm - xBotIm;
                    xBot.re = xBotRe*wRe - xBotIm*wIm;
                    xBot.im = xBotRe*wIm + xBotIm*wRe;

                    // Advance butterfly to next top & bottom positions
                    xTop = xTop.next;
                    xBot = xBot.next;

                    // Update the twiddle factor, via complex multiply
                    // by unit vector with the appropriate angle
                    // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
                    double tRe = wRe;
                    wRe = wRe*wMulRe - wIm*wMulIm;
                    wIm = tRe*wMulIm + wIm*wMulRe;
                }
            }

            numFlies >>= 1;     // Divide by 2 by right shift
            span >>= 1;
            spacing >>= 1;
            wIndexStep <<= 1;   // Multiply by 2 by left shift
        }

        // The algorithm leaves the result in a scrambled order.
        // Unscramble while copying values from the complex
        // linked list elements back to the input/output vectors.
        x = m_X[0];
        while (x != null)
        {
            uint target = x.revTgt;
            xRe[target] = x.re;
            xIm[target] = x.im;
            x = x.next;
        }
    }

    /**
     * Do bit reversal of specified number of places of an int
     * For example, 1101 bit-reversed is 1011
     *
     * @param   x       Number to be bit-reverse.
     * @param   numBits Number of bits in the number.
     */
    private uint BitReverse(
        uint x,
        uint numBits)
    {
        uint y = 0;
        for (uint i = 0; i < numBits; i++)
        {
            y <<= 1;
            y |= x & 0x0001;
            x >>= 1;
        }
        return y;
    }

}

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

How do you get total amount of RAM the computer has?

.NIT has a limit to the amount of memory it can access of the total. Theres a percentage, and then 2 GB in xp was the hard ceiling.

You could have 4 GB in it, and it would kill the app when it hit 2GB.

Also in 64 bit mode, there is a percentage of memory you can use out of the system, so I'm not sure if you can ask for the whole thing or if this is specifically guarded against.

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

assuming your project is maven based, add it to your POM:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>

Save > Build > and test connection again. It works! Your actual mysql java connector version may vary.

Blocks and yields in Ruby

In Ruby, a block is basically a chunk of code that can be passed to and executed by any method. Blocks are always used with methods, which usually feed data to them (as arguments).

Blocks are widely used in Ruby gems (including Rails) and in well-written Ruby code. They are not objects, hence cannot be assigned to variables.

Basic Syntax

A block is a piece of code enclosed by { } or do..end. By convention, the curly brace syntax should be used for single-line blocks and the do..end syntax should be used for multi-line blocks.

{ # This is a single line block }

do
  # This is a multi-line block
end 

Any method can receive a block as an implicit argument. A block is executed by the yield statement within a method. The basic syntax is:

def meditate
  print "Today we will practice zazen"
  yield # This indicates the method is expecting a block
end 

# We are passing a block as an argument to the meditate method
meditate { print " for 40 minutes." }

Output:
Today we will practice zazen for 40 minutes.

When the yield statement is reached, the meditate method yields control to the block, the code within the block is executed and control is returned to the method, which resumes execution immediately following the yield statement.

When a method contains a yield statement, it is expecting to receive a block at calling time. If a block is not provided, an exception will be thrown once the yield statement is reached. We can make the block optional and avoid an exception from being raised:

def meditate
  puts "Today we will practice zazen."
  yield if block_given? 
end meditate

Output:
Today we will practice zazen. 

It is not possible to pass multiple blocks to a method. Each method can receive only one block.

See more at: http://www.zenruby.info/2016/04/introduction-to-blocks-in-ruby.html

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

How to print a two dimensional array?

How about trying this?

public static void main (String [] args)
{
   int [] [] listTwo = new int [5][5];
    // 2 Dimensional array 
    int x = 0;
    int y = 0;
    while (x < 5) {
        listTwo[x][y] = (int)(Math.random()*10);

        while (y <5){
            listTwo [x] [y] = (int)(Math.random()*10);
            System.out.print(listTwo[x][y]+" | ");
            y++;                
        }
        System.out.println("");
        y=0;
        x++;
    }
}

Split list into smaller lists (split in half)

If you don't care about the order...

def split(list):  
    return list[::2], list[1::2]

list[::2] gets every second element in the list starting from the 0th element.
list[1::2] gets every second element in the list starting from the 1st element.

Sending a mail from a linux shell script

SEND MAIL FROM LINUX TO GMAIL

USING POSTFIX

1: install software

Debian and Ubuntu:

apt-get update && apt-get install postfix mailutils

OpenSUSE:

zypper update && zypper install postfix mailx cyrus-sasl

Fedora:

dnf update && dnf install postfix mailx

CentOS:

yum update && yum install postfix mailx cyrus-sasl cyrus-sasl-plain

Arch Linux:

pacman -Sy postfix mailutils

FreeBSD:

portsnap fetch extract update

cd /usr/ports/mail/postfix

make config

in configaration select SASL support

make install clean

pkg install mailx

2. Configure Gmail

/etc/postfix. Create or edit the password file:

vim /etc/postfix/sasl_passwd

i m using vim u can use any file editer like nano, cat .....

>Ubuntu, Fedora, CentOS,Debian, OpenSUSE, Arch Linux:

add this

where user replace with your mailname and password is your gmail password

[smtp.gmail.com]:587    [email protected]:password

Save and close the file and Make it accessible only by root: becouse its an sensitive content which contains ur password

chmod 600 /usr/local/etc/postfix/sasl_passwd

>FreeBSD:

directory /usr/local/etc/postfix.

vim /usr/local/etc/postfix/sasl_passwd

Add the line:

[smtp.gmail.com]:587    [email protected]:password

Save and Make it accessible only by root:

chmod 600 /usr/local/etc/postfix/sasl_passwd

3. Postfix configuration

configuration file main.cf

6 parameters we must set in the Postfix

Ubuntu, Arch Linux,Debian:

edit

 vim /etc/postfix/main.cf

modify the following values:

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

smtp_sasl_security_options which in configuration will be set to empty, to ensure that no Gmail-incompatible security options are used.

save and close

as like for

OpenSUSE:

vim /etc/postfix/main.cf

modify

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/ca-bundle.pem

it also requires configuration of file master.cf

modify:

vim /etc/postfix/master.cf

as by uncommenting this line(remove #)

#tlsmgr unix - - n 1000? 1 tlsmg

save and close

Fedora, CentOS:

vim /etc/postfix/main.cf

modify

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt

FreeBSD:

vim /usr/local/etc/postfix/main.cf

modify:

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/usr/local/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/mail/certs/cacert.pem

save and close this

4. Process Password File:

Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:

postmap /etc/postfix/sasl_passwd

for freeBSD

postmap /usr/local/etc/postfix/sasl_passwd

4.1) Restart postfix

Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:

systemctl restart postfix.service

for FreeBSD:

service postfix onestart
nano /etc/rc.conf

add

postfix_enable=YES

save then run to start

service postfix start

5. Enable "Less Secure Apps" In Gmail using help of below link

https://support.google.com/accounts/answer/6010255

6. Send A Test Email

mail -s "subject" [email protected]

press enter

add body of mail as your wish press enter then press ctrl+d for proper termination

if it not working check the all steps again and check if u enable "less secure app" in your gmail

then restart postfix if u modify anything in that

for shell script create the .sh file and add 6 step command as your requirement

for example just for a sample

#!/bin/bash
REALVALUE=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')
THRESHOLD=80

if [ "$REALVALUE" -gt "$THRESHOLD" ] ; then
    mail -s 'Disk Space Alert' [email protected] << EOF
Your root partition remaining free space is critically low. Used: $REALVALUE%
EOF
fi

The script sends an email when the disk usage rises above the percentage specified by the THRESHOLD varialbe (80% here).

A button to start php script, how?

This one works for me:

index.php

    <?php
       if(isset($_GET['action']))
              {
                 //your code
                 echo 'Welcome';
              }
    ?>


    <form id="frm" method="post"  action="?action" >
    <input type="submit" value="Submit" id="submit" />
    </form>

This link can be helpful:

https://blogs.msdn.microsoft.com/brian_swan/2010/02/08/getting-started-with-the-sql-server-driver-for-php/

How can I upload files asynchronously?

I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

$(document).ready(function() {
  $("#uploadbutton").jsupload({
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);
    }
  });
});

Custom "confirm" dialog in JavaScript?

I managed to find the solution that will allow you to do this using default confirm() with minimum of changes if you have a lot of confirm() actions through out you code. This example uses jQuery and Bootstrap but the same thing can be accomplished using other libraries as well. You can just copy paste this and it should work right away

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Project Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <!--[if lt IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div class="container">
    <h1>Custom Confirm</h1>
    <button id="action"> Action </button> 
    <button class='another-one'> Another </button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>

<script type="text/javascript">

    document.body.innerHTML += `<div class="modal fade"  style="top:20vh" id="customDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
    <div class="modal-content">
    <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>
    <div class="modal-body">

    </div>
    <div class="modal-footer">
    <button type="button" id='dialog-cancel' class="btn btn-secondary">Cancel</button>
    <button type="button" id='dialog-ok' class="btn btn-primary">Ok</button>
    </div>
    </div>
    </div>
    </div>`;

    function showModal(text) {

        $('#customDialog .modal-body').html(text);
        $('#customDialog').modal('show');

    }

    function startInterval(element) {

         interval = setInterval(function(){

           if ( window.isConfirmed != null ) {

              window.confirm = function() {

                  return window.isConfirmed;
              }

              elConfrimInit.trigger('click');

              clearInterval(interval);
              window.isConfirmed = null;
              window.confirm = function(text) {
                showModal(text);
                startInterval();
            }

           }

        }, 500);

    }

    window.isConfirmed = null;
    window.confirm = function(text,elem = null) {
        elConfrimInit = elem;
        showModal(text);
        startInterval();
    }

    $(document).on('click','#dialog-ok', function(){

        isConfirmed = true;
        $('#customDialog').modal('hide');

    });

    $(document).on('click','#dialog-cancel', function(){

        isConfirmed = false;
        $('#customDialog').modal('hide');

   });

   $('#action').on('click', function(e) {

 

        if ( confirm('Are you sure?',$(this)) ) {

            alert('confrmed');
        }
        else {
            alert('not confimed');
        }
    });

    $('.another-one').on('click', function(e) {


        if ( confirm('Are really, really, really sure ? you sure?',$(this)) ) {

            alert('confirmed');
        }
        else {
            alert('not confimed');
        }
    });


</script>
</body>
</html>

This is the whole example. After you implement it you will be able to use it like this:

if ( confirm('Are you sure?',$(this)) )

Start and stop a timer PHP

Also you can use HRTime package. It has a class StopWatch.

Using SQL LOADER in Oracle to import CSV file

Try this

load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)

In command prompt:

sqlldr system@databasename/password control='control file location'

jQuery: Currency Format Number

Divide by 1000, and use .toFixed(3) to fix the number of decimal places.

var output = (input/1000).toFixed(3);

[EDIT]

The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.

In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.

A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Another yet simple solution is to paste these line into the build.gradle file

dependencies {

    //import of gridlayout
    compile 'com.android.support:gridlayout-v7:19.0.0'
    compile 'com.android.support:appcompat-v7:+'
}

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

How to declare empty list and then add string in scala?

Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.

How to maximize a plt.show() window using Python

I get mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame' as well.

Then I looked through the attributes mng has, and I found this:

mng.window.showMaximized()

That worked for me.

So for people who have the same trouble, you may try this.

By the way, my Matplotlib version is 1.3.1.

Server configuration is missing in Eclipse

In Eclipse Neo
1. Window -> Show view -> Servers
2. Right click on server -> choose Properties
3. From General Tab -> Switch Location

Maven2: Best practice for Enterprise Project (EAR file)

This is a good example of the maven-ear-plugin part.

You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is

maven-archetype-j2ee-simple

Convert UTC Epoch to local date

Considering, you have epoch_time available,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format

Split Strings into words with multiple word boundary delimiters

Heres my take on it....

def split_string(source,splitlist):
    splits = frozenset(splitlist)
    l = []
    s1 = ""
    for c in source:
        if c in splits:
            if s1:
                l.append(s1)
                s1 = ""
        else:
            print s1
            s1 = s1 + c
    if s1:
        l.append(s1)
    return l

>>>out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",")
>>>print out
>>>['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']

ASP.NET GridView RowIndex As CommandArgument

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

What kind of document library information do you want in the view? How do you want the user to filter the view?

In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx

You will need Microsoft Office SharePoint Designer.

You can present different views of you folders using the data view filter and sorting controls.

You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?

Mac zip compress without __MACOSX folder?

I'm using this Automator Shell Script to fix it after. It's showing up as contextual menu item (right clicking on any file showing up in Finder).

while read -r p; do
  zip -d "$p" __MACOSX/\* || true
  zip -d "$p" \*/.DS_Store || true
done
  1. Create a new Service with Automator
  2. Select "Files and Folders" in "Finder"
  3. Add a "Shell Script Action"

automator shell script

contextual menu item in Finder

Use python requests to download CSV

To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently.

import requests
from contextlib import closing
import csv

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
    for row in reader:
        print row   

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

How to update multiple columns in single update statement in DB2

I know it's an old question, but I just had to find solution for multiple rows update where multiple records had to updated with different values based on their IDs and I found that I can use a a scalar-subselect:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP='000030'

(with WHERE optional, of course)

Also, I found that it is critical to specify that no NULL values would not be used in this update (in case not all records in first table have corresponding record in the second one), this way:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP IN (SELECT EMPNO FROM EMPLOYEE)

Source: https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafyupdatesub.htm

Display PDF within web browser

You can use the <embed> tag with the source of the file in the src attribute. This uses the native browser PDF viewer.

<embed src="your_pdf_src" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">

Live example:

_x000D_
_x000D_
<embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
_x000D_
_x000D_
_x000D_

Loading the PDF inside a snippet won't work, since the frame into which the plugin is loading is sandboxed.

Tested in Chrome and Firefox. See it in action.

Java ArrayList clear() function

it's not true the clear() function clear the Arraylist and start from index 0

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

List of all unique characters in a string?

I have an idea. Why not use the ascii_lowercase constant?

For example, running the following code:

# string module, contains constant ascii_lowercase which is all the lowercase
# letters of the English alphabet
import string
# Example value of s, a string
s = 'aaabcabccd'
# Result variable to store the resulting string
result = ''
# Goes through each letter in the alphabet and checks how many times it appears.
# If a letter appears at least oce, then it is added to the result variable
for letter in string.ascii_letters:
    if s.count(letter) >= 1:
        result+=letter

# Optional three lines to convert result variable to a list for sorting
# and then back to a string
result = list(result)
result.sort()
result = ''.join(result)

print(result)

Will print 'abcd'

There you go, all duplicates removed and optionally sorted

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

ImportError: No module named pythoncom

Just go to cmd and install pip install pywin32 pythoncom is part of pywin32 for API window extension.... good luck

How to pass a parameter like title, summary and image in a Facebook sharer URL

Looks like Facebook disabled passing parameters to the sharer.

We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/

Create dataframe from a matrix

melt() from the reshape2 package gets you close ...

library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
#   time variable value
# 1  0.0      C_0   0.1
# 2  0.5      C_0   0.2
# 3  1.0      C_0   0.3
# 4  0.0      C_1   0.3
# 5  0.5      C_1   0.4
# 6  1.0      C_1   0.5

... although you may want to post-process its results to get your preferred column names and ordering.

setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
#   name time val
# 1  C_0  0.0 0.1
# 2  C_0  0.5 0.2
# 3  C_0  1.0 0.3
# 4  C_1  0.0 0.3
# 5  C_1  0.5 0.4
# 6  C_1  1.0 0.5

Php, wait 5 seconds before executing an action

before starting your actions, use

 sleep(5);

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

VSCode: How to Split Editor Vertically

Simply in windows

ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)

SyntaxError: unexpected EOF while parsing

This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF:

print(9, not (a==7 and b==6)

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

"Could not find Developer Disk Image"

I am facing the same issue on Xcode 7.3 and my device version is iOS 10.

This error is shown when your Xcode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.

We can solve this issue by following the below steps:-

  • Open Finder select Applications
  • Right click on Xcode 8, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Copy the 10.0 folder (or above for later version).
  • Back in Finder select Applications again
  • Right click on Xcode 7.3, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Paste the 10.0 folder

If everything worked properly, your Xcode has a new developer disk image. Close the finder now, and quit your Xcode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.

Thanks

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(System.in);
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char) System.in.read();

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

  
from chromedriver_py import binary_path
 
 
chrome_options = webdriver.ChromeOptions()
   chrome_options.add_argument('--headless')
   chrome_options.add_argument('--no-sandbox')
   chrome_options.add_argument('--disable-gpu')
   chrome_options.add_argument('--window-size=1280x1696')
   chrome_options.add_argument('--user-data-dir=/tmp/user-data')
   chrome_options.add_argument('--hide-scrollbars')
   chrome_options.add_argument('--enable-logging')
   chrome_options.add_argument('--log-level=0')
   chrome_options.add_argument('--v=99')
   chrome_options.add_argument('--single-process')
   chrome_options.add_argument('--data-path=/tmp/data-path')
   chrome_options.add_argument('--ignore-certificate-errors')
   chrome_options.add_argument('--homedir=/tmp')
   chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir')
   chrome_options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')
   
  driver = webdriver.Chrome(executable_path = binary_path,options=chrome_options)

What does "Object reference not set to an instance of an object" mean?

Variables in .NET are either reference types or value types. Value types are primitives such as integers and booleans or structures (and can be identified because they inherit from System.ValueType). Boolean variables, when declared, have a default value:

bool mybool;
//mybool == false

Reference types, when declared, do not have a default value:

class ExampleClass
{
}

ExampleClass exampleClass; //== null

If you try to access a member of a class instance using a null reference then you get a System.NullReferenceException. Which is the same as Object reference not set to an instance of an object.

The following code is a simple way of reproducing this:

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();
    returnedClass.AnotherExampleMethod(); //NullReferenceException here.
}

class ExampleClass
{
    public ReturnedClass ExampleMethod()
    {
        return null;
    }
}

class ReturnedClass
{
    public void AnotherExampleMethod()
    {
    }
}

This is a very common error and can occur because of all kinds of reasons. The root cause really depends on the specific scenario that you've encountered.

If you are using an API or invoking methods that may return null then it's important to handle this gracefully. The main method above can be modified in such a way that the NullReferenceException should never be seen by a user:

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();

    if (returnedClass == null)
    {
        //throw a meaningful exception or give some useful feedback to the user!
        return;
    }

    returnedClass.AnotherExampleMethod();
}

All of the above really just hints of .NET Type Fundamentals, for further information I'd recommend either picking up CLR via C# or reading this MSDN article by the same author - Jeffrey Richter. Also check out, much more complex, example of when you can encounter a NullReferenceException.

Some teams using Resharper make use of JetBrains attributes to annotate code to highlight where nulls are (not) expected.

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

What is the best way to convert an array to a hash in Ruby

NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.

This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.


Warning! Solutions using flatten will not preserve Array keys or values!

Building on @John Topley's popular answer, let's try:

a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]

This throws an error:

ArgumentError: odd number of arguments for Hash
        from (irb):10:in `[]'
        from (irb):10

The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.

If you want to use Array keys or values, you can use map:

h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"

This preserves the Array key:

h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}

Shell script variable not empty (-z option)

I think this is the syntax you are looking for:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi

Difference between BYTE and CHAR in column datatypes

Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:

  1. Limits field to 11 BYTE
  2. Limits field to 11 CHARacters


Conclusion: 1 CHAR is not equal to 1 BYTE.

How do I add a simple jQuery script to WordPress?

**#Method 1:**Try to put your jquery code in a separate js file.

Now register that script in functions.php file.

function add_my_script() {
    wp_enqueue_script(
      'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
        array('jquery') 
    );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Now you are done.

Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.

How to clear a chart from a canvas so that hover events cannot be triggered?

When you create one new chart.js canvas, this generate one new iframe hidden, you need delete the canvas and the olds iframes.

$('#canvasChart').remove(); 
$('iframe.chartjs-hidden-iframe').remove(); 
$('#graph-container').append('<canvas id="canvasChart"><canvas>'); 
var ctx = document.getElementById("canvasChart"); 
var myChart = new Chart(ctx, { blablabla });

reference: https://github.com/zebus3d/javascript/blob/master/chartJS_filtering_with_checkboxs.html

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank


¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

correct way of comparing string jquery operator =

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

What is the "continue" keyword and how does it work in Java?

Basically in java, continue is a statement. So continue statement is normally used with the loops to skip the current iteration.

For how and when it is used in java, refer link below. It has got explanation with example.

https://www.flowerbrackets.com/continue-java-example/

Hope it helps !!

Jump into interface implementation in Eclipse IDE

The best solution would be Ctrl+Alt+I.

How to generate an MD5 file hash in JavaScript?

If you don't want to use libraries or other things, you can use this native javascript approach:

_x000D_
_x000D_
var MD5 = function(d){var r = M(V(Y(X(d),8*d.length)));return r.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}_x000D_
_x000D_
/** NORMAL words**/_x000D_
var value = 'test';_x000D_
_x000D_
var result = MD5(value);_x000D_
 _x000D_
document.body.innerHTML = 'hash -  normal words: ' + result;_x000D_
_x000D_
/** NON ENGLISH words**/_x000D_
value = '????'_x000D_
_x000D_
//unescape() can be deprecated for the new browser versions_x000D_
result = MD5(unescape(encodeURIComponent(value)));_x000D_
_x000D_
document.body.innerHTML += '<br><br>hash - non english words: ' + result;_x000D_
 
_x000D_
_x000D_
_x000D_

For non english words you may need to use unescape() and the encodeURIComponent() methods.

How can I iterate over an enum?

With c++11, there actually is an alternative: writing a simple templatized custom iterator.

let's assume your enum is

enum class foo {
  one,
  two,
  three
};

This generic code will do the trick, quite efficiently - place in a generic header, it'll serve you for any enum you may need to iterate over:

#include <type_traits>
template < typename C, C beginVal, C endVal>
class Iterator {
  typedef typename std::underlying_type<C>::type val_t;
  int val;
public:
  Iterator(const C & f) : val(static_cast<val_t>(f)) {}
  Iterator() : val(static_cast<val_t>(beginVal)) {}
  Iterator operator++() {
    ++val;
    return *this;
  }
  C operator*() { return static_cast<C>(val); }
  Iterator begin() { return *this; } //default ctor is good
  Iterator end() {
      static const Iterator endIter=++Iterator(endVal); // cache it
      return endIter;
  }
  bool operator!=(const Iterator& i) { return val != i.val; }
};

You'll need to specialize it

typedef Iterator<foo, foo::one, foo::three> fooIterator;

And then you can iterate using range-for

for (foo i : fooIterator() ) { //notice the parentheses!
   do_stuff(i);
}

The assumption that you don't have gaps in your enum is still true; there is no assumption on the number of bits actually needed to store the enum value (thanks to std::underlying_type)

Which .NET Dependency Injection frameworks are worth looking into?

I'm a huge fan of Castle. I love the facilities it also provides beyond the IoC Container story. It really simplfies using NHibernate, logging, AOP, etc. I also use Binsor for configuration with Boo and have really fallen in love with Boo as a language because of it.

Why is sed not recognizing \t as a tab?

Using Bash you may insert a TAB character programmatically like so:

TAB=$'\t' 
echo 'line' | sed "s/.*/${TAB}&/g" 
echo 'line' | sed 's/.*/'"${TAB}"'&/g'   # use of Bash string concatenation

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

send mail from linux terminal in one line

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

I had the same issue when upgrading from Tomcat 7 to 8: a continuous large flood of log warnings about cache.

1. Short Answer

Add this within the Context xml element of your $CATALINA_BASE/conf/context.xml:

<!-- The default value is 10240 kbytes, even when not added to context.xml.
So increase it high enough, until the problem disappears, for example set it to 
a value 5 times as high: 51200. -->
<Resources cacheMaxSize="51200" />

So the default is 10240 (10 mbyte), so set a size higher than this. Than tune for optimum settings where the warnings disappear. Note that the warnings may come back under higher traffic situations.

1.1 The cause (short explanation)

The problem is caused by Tomcat being unable to reach its target cache size due to cache entries that are less than the TTL of those entries. So Tomcat didn't have enough cache entries that it could expire, because they were too fresh, so it couldn't free enough cache and thus outputs warnings.

The problem didn't appear in Tomcat 7 because Tomcat 7 simply didn't output warnings in this situation. (Causing you and me to use poor cache settings without being notified.)

The problem appears when receiving a relative large amount of HTTP requests for resources (usually static) in a relative short time period compared to the size and TTL of the cache. If the cache is reaching its maximum (10mb by default) with more than 95% of its size with fresh cache entries (fresh means less than less than 5 seconds in cache), than you will get a warning message for each webResource that Tomcat tries to load in the cache.

1.2 Optional info

Use JMX if you need to tune cacheMaxSize on a running server without rebooting it.

The quickest fix would be to completely disable cache: <Resources cachingAllowed="false" />, but that's suboptimal, so increase cacheMaxSize as I just described.

2. Long Answer

2.1 Background information

A WebSource is a file or directory in a web application. For performance reasons, Tomcat can cache WebSources. The maximum of the static resource cache (all resources in total) is by default 10240 kbyte (10 mbyte). A webResource is loaded into the cache when the webResource is requested (for example when loading a static image), it's then called a cache entry. Every cache entry has a TTL (time to live), which is the time that the cache entry is allowed to stay in the cache. When the TTL expires, the cache entry is eligible to be removed from the cache. The default value of the cacheTTL is 5000 milliseconds (5 seconds).

There is more to tell about caching, but that is irrelevant for the problem.

2.2 The cause

The following code from the Cache class shows the caching policy in detail:

152  // Content will not be cached but we still need metadata size
153 long delta = cacheEntry.getSize();
154 size.addAndGet(delta);
156 if (size.get() > maxSize) {
157 // Process resources unordered for speed. Trades cache
158 // efficiency (younger entries may be evicted before older
159 // ones) for speed since this is on the critical path for
160 // request processing
161 long targetSize =
162 maxSize * (100 - TARGET_FREE_PERCENT_GET) / 100;
163 long newSize = evict(
164 targetSize, resourceCache.values().iterator());
165 if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }
171 }

When loading a webResource, the code calculates the new size of the cache. If the calculated size is larger than the default maximum size, than one or more cached entries have to be removed, otherwise the new size will exceed the maximum. So the code will calculate a "targetSize", which is the size the cache wants to stay under (as an optimum), which is by default 95% of the maximum. In order to reach this targetSize, entries have to be removed/evicted from the cache. This is done using the following code:

215  private long evict(long targetSize, Iterator<CachedResource> iter) {
217 long now = System.currentTimeMillis();
219 long newSize = size.get();
221 while (newSize > targetSize && iter.hasNext()) {
222 CachedResource resource = iter.next();
224 // Don't expire anything that has been checked within the TTL
225 if (resource.getNextCheck() > now) {
226 continue;
227 }
229 // Remove the entry from the cache
230 removeCacheEntry(resource.getWebappPath());
232 newSize = size.get();
233 }
235 return newSize;
236 }

So a cache entry is removed when its TTL is expired and the targetSize hasn't been reached yet.

After the attempt to free cache by evicting cache entries, the code will do:

165  if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }

So if after the attempt to free cache, the size still exceeds the maximum, it will show the warning message about being unable to free:

cache.addFail=Unable to add the resource at [{0}] to the cache for web application [{1}] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

2.3 The problem

So as the warning message says, the problem is

insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

If your web application loads a lot of uncached webResources (about maximum of cache, by default 10mb) within a short time (5 seconds), then you'll get the warning.

The confusing part is that Tomcat 7 didn't show the warning. This is simply caused by this Tomcat 7 code:

1606  // Add new entry to cache
1607 synchronized (cache) {
1608 // Check cache size, and remove elements if too big
1609 if ((cache.lookup(name) == null) && cache.allocate(entry.size)) {
1610 cache.load(entry);
1611 }
1612 }

combined with:

231  while (toFree > 0) {
232 if (attempts == maxAllocateIterations) {
233 // Give up, no changes are made to the current cache
234 return false;
235 }

So Tomcat 7 simply doesn't output any warning at all when it's unable to free cache, whereas Tomcat 8 will output a warning.

So if you are using Tomcat 8 with the same default caching configuration as Tomcat 7, and you got warnings in Tomcat 8, than your (and mine) caching settings of Tomcat 7 were performing poorly without warning.

2.4 Solutions

There are multiple solutions:

  1. Increase cache (recommended)
  2. Lower the TTL (not recommended)
  3. Suppress cache log warnings (not recommended)
  4. Disable cache

2.4.1. Increase cache (recommended)

As described here: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html

By adding <Resources cacheMaxSize="XXXXX" /> within the Context element in $CATALINA_BASE/conf/context.xml, where "XXXXX" stands for an increased cache size, specified in kbytes. The default is 10240 (10 mbyte), so set a size higher than this.

You'll have to tune for optimum settings. Note that the problem may come back when you suddenly have an increase in traffic/resource requests.

To avoid having to restart the server every time you want to try a new cache size, you can change it without restarting by using JMX.

To enable JMX, add this to $CATALINA_BASE/conf/server.xml within the Server element: <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="6767" rmiServerPortPlatform="6768" /> and download catalina-jmx-remote.jar from https://tomcat.apache.org/download-80.cgi and put it in $CATALINA_HOME/lib. Then use jConsole (shipped by default with the Java JDK) to connect over JMX to the server and look through the settings for settings to increase the cache size while the server is running. Changes in these settings should take affect immediately.

2.4.2. Lower the TTL (not recommended)

Lower the cacheTtl value by something lower than 5000 milliseconds and tune for optimal settings.

For example: <Resources cacheTtl="2000" />

This comes effectively down to having and filling a cache in ram without using it.

2.4.3. Suppress cache log warnings (not recommended)

Configure logging to disable the logger for org.apache.catalina.webresources.Cache.

For more info about logging in Tomcat: http://tomcat.apache.org/tomcat-8.0-doc/logging.html

2.4.4. Disable cache

You can disable the cache by setting cachingAllowed to false. <Resources cachingAllowed="false" />

Although I can remember that in a beta version of Tomcat 8, I was using JMX to disable the cache. (Not sure why exactly, but there may be a problem with disabling the cache via server.xml.)

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

Making view resize to its parent when added with addSubview

You can always do it in your UIViews - (void)didMoveToSuperview method. It will get called when added or removed from your parent (nil when removed). At that point in time just set your size to that of your parent. From that point on the autoresize mask should work properly.

Pipe to/from the clipboard in Bash script

There are a couple ways. Some of the ways that have been mentioned include (I think) tmux, screen, vim, emacs, and the shell. I don't know emacs or screen, so I'll go over the other three.

Tmux

While not an X selection, tmux has a copy mode accessible via prefix-[ (prefix is Ctrl+B by default). The buffer used for this mode is separate and exclusive to tmux, which opens up quite a few possibilities and makes it more versatile than the X selections in the right situations.

To exit this mode, hit q; to navigate, use your vim or emacs binding (default = vim), so hjkl for movement, v/V/C-v for character/line/block selection, etc. When you have your selection, hit Enter to copy and exit the mode.

To paste from this buffer, use prefix-].

Shell

Any installation of X11 seems to come with two programs by default: xclip and xsel (kinda like how it also comes with both startx and xinit). Most of the other answers mention xclip, and I really like xsel for its brevity, so I'm going to cover xsel.

From xsel(1x):

Input options

-a, --append

append standard input to the selection. Implies -i.

-f, --follow

append to selection as standard input grows. Implies -i.

-i, --input

read standard input into the selection.

Output options

-o, --output

write the selection to standard output.

Action options

-c, --clear

clear the selection. Overrides all input options.

-d, --delete

Request that the current selection be deleted. This not only clears the selection, but also requests to the program in which the selection resides that the selected contents be deleted. Overrides all input options.

Selection options

-p, --primary

operate on the PRIMARY selection (default).

-s, --secondary

operate on the SECONDARY selection.

-b, --clipboard

operate on the CLIPBOARD selection.

And that's about all you need to know. p (or nothing) for PRIMARY, s for SECONDARY, b for CLIPBOARD, o for output.

Example: say I want to copy the output of foo from a TTY and paste it to a webpage for a bug report. To do this, it would be ideal to copy to/from the TTY/X session. So the question becomes how do I access the clipboard from the TTY?

For this example, we'll assume the X session is on display :1.

$ foo -v
Error: not a real TTY
details:
blah blah @ 0x0000000040abeaf4
blah blah @ 0x0000000040abeaf8
blah blah @ 0x0000000040abeafc
blah blah @ 0x0000000040abeb00
...
$ foo -v | DISPLAY=:1 xsel -b # copies it into clipboard of display :1

Then I can Ctrl-V it into the form as per usual.

Now say that someone on the support site gives me a command to run to fix the problem. It's complicated and long.

$ DISPLAY=:1 xsel -bo
sudo foo --update --clear-cache --source-list="http://foo-software.com/repository/foo/debian/ubuntu/xenial/164914519191464/sources.txt"
$ $(DISPLAY=:1 xsel -bo)
Password for braden:
UPDATING %%%%%%%%%%%%%%%%%%%%%%% 100.00%
Clearing cache...
Fetching sources...
Reticulating splines...
Watering trees...
Climbing mountains...
Looking advanced...
Done.
$ foo
Thank you for your order. A pizza should arrive at your house in the next 20 minutes. Your total is $6.99

Pizza ordering seems like a productive use of the command line.

...moving on.

Vim

If compiled with +clipboard (This is important! Check your vim --version), Vim should have access to the X PRIMARY and CLIPBOARD selections. The two selections are accessible from the * and + registers, respectively, and may be written to and read from at your leisure the same as any other register. For example:

:%y+    ; copy/yank (y) everything (%) into the CLIPBOARD selection (+)
"+p     ; select (") the CLIPBOARD selection (+) and paste/put it
ggVG"+y ; Alternative version of the first example

If your copy of vim doesn't directly support access to X selections, though, it's not the end of the world. You can just use the xsel technique as described in the last section.

:r ! xsel -bo ; read  (r) from the stdout of (!) `xsel -bo`
:w ! xsel -b  ; write (w) to the stdin of    (!) `xsel -b`

Bind a couple key combos and you should be good.

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

How to install gdb (debugger) in Mac OSX El Capitan?

Install Homebrew first :

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run this : brew install gdb

Pretty printing JSON from Jackson 2.2's ObjectMapper

According to mkyong, the magic incantation is defaultPrintingWriter to pretty print JSON:

Newer versions:

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));

Older versions:

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));

Seems I jumped the gun a tad quickly. You could try gson, whose constructor supports pretty-printing:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Hope this helps...

How to make a div with a circular shape?

HTML div elements, unlike SVG circle primitives, are always rectangular.

You could use round corners (i.e. CSS border-radius) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:

_x000D_
_x000D_
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
_x000D_
_x000D_

Java LinkedHashMap get first or last entry

I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods