Programs & Examples On #Uitypeeditor

SQL NVARCHAR and VARCHAR Limits

Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:

CREATE PROCEDURE ExecuteMyHugeQuery
    @SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
    -- Now, if the length is greater than some arbitrary value
    -- Let's say 2000 for this example
    -- Let's chunk it
    -- Let's also assume we won't allow anything larger than 8000 total
    DECLARE @len INT
    SELECT @len = LEN(@SQL)

    IF (@len > 8000)
    BEGIN
        RAISERROR ('The query cannot be larger than 8000 characters total.',
                   16,
                   1);
    END

    -- Let's declare our possible chunks
    DECLARE @Chunk1 VARCHAR(2000),
            @Chunk2 VARCHAR(2000),
            @Chunk3 VARCHAR(2000),
            @Chunk4 VARCHAR(2000)

    SELECT @Chunk1 = '',
           @Chunk2 = '',
           @Chunk3 = '',
           @Chunk4 = ''

    IF (@len > 2000)
    BEGIN
        -- Let's set the right chunks
        -- We already know we need two chunks so let's set the first
        SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)

        -- Let's see if we need three chunks
        IF (@len > 4000)
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)

            -- Let's see if we need four chunks
            IF (@len > 6000)
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
                SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
            END
              ELSE
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
            END
        END
          ELSE
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
        END
    END

    -- Alright, now that we've broken it down, let's execute it
    EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

inetmgr then come to Application pool->Advanced setting of your pool-> will have the option "Enable 32-Bit Applications" set to true; and restart IIS. check again.!

What's the difference between commit() and apply() in SharedPreferences

Use apply().

It writes the changes to the RAM immediately and waits and writes it to the internal storage(the actual preference file) after. Commit writes the changes synchronously and directly to the file.

Concatenating bits in VHDL

The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only

Toggle visibility property of div

There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}

How can I solve ORA-00911: invalid character error?

I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT statement, I had some commented notes that included special characters. Removing the comments resolved the issue.

Intent from Fragment to Activity

use getContext() instead of MainActivity.this

Intent intent = new Intent(getContext(), SecondActivity.class);
startActivity(start);

How do I generate a stream from a string?

Use the MemoryStream class, calling Encoding.GetBytes to turn your string into an array of bytes first.

Do you subsequently need a TextReader on the stream? If so, you could supply a StringReader directly, and bypass the MemoryStream and Encoding steps.

How do I upgrade PHP in Mac OS X?

best way to upgrade is compile it from source

see this tutorial that may be helful for you

http://www.computersnyou.com/2012/09/how-to-upgrade-php-in-mac-osx-compiling.html

Disable firefox same origin policy

In about:config add content.cors.disable (empty string).

Java Multithreading concept and join() method

My Comments:

When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.

Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.

1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.

So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.

2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.

about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2

and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2

This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.

What is the purpose of backbone.js?

It also adds routing using controllers and views with KVO. You'll be able to develop "AJAXy" applications with it.

See it as a lightweight Sproutcore or Cappuccino framework.

Clearing UIWebview cache

I actually think it may retain cached information when you close out the UIWebView. I've tried removing a UIWebView from my UIViewController, releasing it, then creating a new one. The new one remembered exactly where I was at when I went back to an address without having to reload everything (it remembered my previous UIWebView was logged in).

So a couple of suggestions:

[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];

This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

After that, you can try deleting any associated cookies with the UIWebView:

for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

    if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

Swift 3:

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

Command to get latest Git commit hash from a branch

Use git ls-remote git://github.com/<user>/<project>.git. For example, my trac-backlog project gives:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0    HEAD
4652257768acef90b9af560295b02d0ac6e7702c    refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3    refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0    refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1    refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2    refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400    refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726    refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24    refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3    refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69    refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd    refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5    refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125    refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d    refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1    refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708    refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57    refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c    refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070    refs/tags/0.3.0^{}

Just grep for the one you need and cut it out:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
   grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Or, you can specify which refs you want on the command line and avoid the grep with:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
   cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Note: it doesn't have to be the git:// URL. It could be https:// or [email protected]: too.

Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:

git rev-parse branch-name

It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:

git rev-parse HEAD

IntelliJ cannot find any declarations

If you see red circle on the icon of Java files, and got warning like "cannot find declaration to go to". Then you can do something below:

  1. Right click root folder of your project/module.
  2. Mark Directory As -> Excluded.

enter image description here

It works for me. in Windows 7, Intellij 2016.1.1

How to run Linux commands in Java?

Runtime run = Runtime.getRuntime();  
//The best possible I found is to construct a command which you want to execute  
//as a string and use that in exec. If the batch file takes command line arguments  
//the command can be constructed a array of strings and pass the array as input to  
//the exec method. The command can also be passed externally as input to the method.  

Process p = null;  
String cmd = "ls";  
try {  
    p = run.exec(cmd);  

    p.getErrorStream();  
    p.waitFor();

}  
catch (IOException e) {  
    e.printStackTrace();  
    System.out.println("ERROR.RUNNING.CMD");  

}finally{
    p.destroy();
}  

How can I read inputs as numbers?

While in your example, int(input(...)) does the trick in any case, python-future's builtins.input is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2's default behaviour of input trying to be "clever" about the input data type (builtins.input basically just behaves like raw_input).

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

How to pass variable as a parameter in Execute SQL Task SSIS?

A little late to the party, but this is how I did it for an insert:

DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0

SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?

INSERT INTO...

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

How to send email to multiple address using System.Net.Mail

I'm used "for" operator.

try
{
    string s = textBox2.Text;
    string[] f = s.Split(',');

    for (int i = 0; i < f.Length; i++)
    {
        MailMessage message = new MailMessage(); // Create instance of message
        message.To.Add(f[i]); // Add receiver
        message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
        message.Subject = label3.Text; // Set subject
        message.Body = richTextBox1.Text; // Set body of message
        client.Send(message); // Send the message
        message = null; // Clean up
    }

}

catch (Exception ex)
{

    MessageBox.Show(ex.Message);
}

Do I need a content-type header for HTTP GET requests?

Get requests should not have content-type because they do not have request entity (that is, a body)

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

In Android Studio I was trying to set the compileSdkVersion and targetSdkVersion to 19.

My solution was to replace at the bottom of build.gradle, from this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

To the older version of the appcompat library:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
}

How do I use $rootScope in Angular to store variables?

angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
   var a = //something in the scope
   //put it in the root scope
    $rootScope.test = "TEST";
 });

angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
   var b = //get var a from root scope somehow
   //use var b

   $scope.value = $rootScope.test;
   alert($scope.value);

 //    var b = $rootScope.test;
 //  alert(b);
 });

DEMO

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

How to reverse an animation on mouse out after hover

Using transform in combination with transition works flawlessly for me:

.ani-grow {
    -webkit-transition: all 0.5s ease; 
    -moz-transition: all 0.5s ease; 
    -o-transition: all 0.5s ease; 
    -ms-transition: all 0.5s ease; 
    transition: all 0.5s ease; 
}
.ani-grow:hover {
    transform: scale(1.01);
}

How to delete shared preferences data from App in Android

In the class definitions:

private static final String PREFERENCES = "shared_prefs";

private static final SharedPreferences sharedPreferences  = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);

Inside the class:

public static void deleteAllSharedPrefs(){
    sharedPreferences.edit().clear().commit();
}

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

Window.open as modal popup?

That solution will open up a new browser window without the normal features such as address bar and similar.

To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.

(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)

How to quickly and conveniently create a one element arraylist

Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections (formerly known as GS Collections).

The following examples all return a List with a single item.

Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");

There are similar methods for other collections.

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

What is the right way to POST multipart/form-data using curl?

The following syntax fixes it for you:

curl -v -F key1=value1 -F upload=@localfilename URL

What is the difference between server side cookie and client side cookie?

  1. Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already

  2. No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.

  3. BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".

Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:

https://courses.cs.washington.edu/courses/cse154/12au/lectures/slides/lecture21-client-storage.shtml#slide8

A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.

If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?

Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.

Remove specific characters from a string in Python

You can also use a function in order to substitute different kind of regular expression or other pattern with the use of a list. With that, you can mixed regular expression, character class, and really basic text pattern. It's really useful when you need to substitute a lot of elements like HTML ones.

*NB: works with Python 3.x

import re  # Regular expression library


def string_cleanup(x, notwanted):
    for item in notwanted:
        x = re.sub(item, '', x)
    return x

line = "<title>My example: <strong>A text %very% $clean!!</strong></title>"
print("Uncleaned: ", line)

# Get rid of html elements
html_elements = ["<title>", "</title>", "<strong>", "</strong>"]
line = string_cleanup(line, html_elements)
print("1st clean: ", line)

# Get rid of special characters
special_chars = ["[!@#$]", "%"]
line = string_cleanup(line, special_chars)
print("2nd clean: ", line)

In the function string_cleanup, it takes your string x and your list notwanted as arguments. For each item in that list of elements or pattern, if a substitute is needed it will be done.

The output:

Uncleaned:  <title>My example: <strong>A text %very% $clean!!</strong></title>
1st clean:  My example: A text %very% $clean!!
2nd clean:  My example: A text very clean

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

How to run server written in js with Node.js

You don't need to go in node.js prompt, you just need to use standard command promt and write

node c:/node/server.js

this also works:

node c:\node\server.js

and then in your browser:

http://localhost:1337

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

How to get a list of programs running with nohup

Instead of nohup, you should use screen. It achieves the same result - your commands are running "detached". However, you can resume screen sessions and get back into their "hidden" terminal and see recent progress inside that terminal.

screen has a lot of options. Most often I use these:

To start first screen session or to take over of most recent detached one:

screen -Rd 

To detach from current session: Ctrl+ACtrl+D

You can also start multiple screens - read the docs.

Importing lodash into angular2 + typescript application

Partial import from lodash should work in angular 4.1.x using following notation:

let assign = require('lodash/assign');

Or use 'lodash-es' and import in module:

import { assign } from 'lodash-es';

PHP CSV string to array

You should use fgetcsv. Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp or php://memory first:

$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);

Then you will have no problem using fgetcsv:

$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
    $csv[] = $data;
}

$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.

Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php

How to set up java logging using a properties file? (java.util.logging)

I have tried your code in above code don't use [preferences.load(configFile);] statement and it will work.here is running sample code

public static void main(String[]s)
{

    Logger log = Logger.getLogger("MyClass");
    try {
    FileInputStream fis =  new FileInputStream("p.properties");
    LogManager.getLogManager().readConfiguration(fis);
    log.setLevel(Level.FINE);
    log.addHandler(new java.util.logging.ConsoleHandler());
    log.setUseParentHandlers(false);

    log.info("starting myApp");
    fis.close();

    } 
    catch(IOException e) {
    e.printStackTrace();
    }
}

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

What is __future__ in Python used for and how/when to use it, and how it works

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)

How to change a TextView's style at runtime

I did this by creating a new XML file res/values/style.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

I also have an entries in my "strings.xml" file like this:

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>

Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: As from API 23 'setTextAppearance' is deprecated

    myTextView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    //highlight the TextView
                    //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    if (Build.VERSION.SDK_INT < 23) {
       myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
       myTextView.setTextAppearance(R.style.boldText);
    }
     myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
                }
            });

To change it back, you would use this:

if (Build.VERSION.SDK_INT < 23) {
    myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
   myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);

Statistics: combinations in Python

Here is an efficient algorithm for you

for i = 1.....r

   p = p * ( n - i ) / i

print(p)

For example nCr(30,7) = fact(30) / ( fact(7) * fact(23)) = ( 30 * 29 * 28 * 27 * 26 * 25 * 24 ) / (1 * 2 * 3 * 4 * 5 * 6 * 7)

So just run the loop from 1 to r can get the result.


In python:

n,r=5,2
p=n
for i in range(1,r):
   p = p*(n - i)/i
else:
   p = p/(i+1)
print(p)

ValueError: setting an array element with a sequence

The Python ValueError:

ValueError: setting an array element with a sequence.

Means exactly what it says, you're trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.

1. When you pass a python tuple or list to be interpreted as a numpy array element:

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element


numpy.mean([5,(6+7)])              #good

numpy.mean([5,tuple(range(2))])    #Fail, can't convert a tuple into a numpy 
                                   #array element


def foo():
    return 3
numpy.array([2, foo()])            #good


def foo():
    return [3,4]
numpy.array([2, foo()])            #Fail, can't convert a list into a numpy 
                                   #array element

2. By trying to cram a numpy array length > 1 into a numpy array element:

x = np.array([1,2,3])
x[0] = np.array([4])         #good



x = np.array([1,2,3])
x[0] = np.array([4,5])       #Fail, can't convert the numpy array to fit 
                             #into a numpy array element

A numpy array is being created, and numpy doesn't know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn't, Numpy responds that it doesn't know how to set an array element with a sequence.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

Get query from java.sql.PreparedStatement

You could try calling toString() on the prepared statement after you've set the bind values.

PreparedStatement query = connection.prepareStatement(aSQLStatement);
System.out.println("Before : " + query.toString());
query.setString(1, "Hello");
query.setString(2, "World");
System.out.println("After : " + query.toString());

This works when you use the JDBC MySQL driver, but I'm not sure if it will in other cases. You may have to keep track of all the bindings you make and then print those out.

Sample output from above code.

Before : com.mysql.jdbc.JDBC4PreparedStatement@fa9cf: SELECT * FROM test WHERE blah1=** NOT SPECIFIED ** and blah2=** NOT SPECIFIED **
After : com.mysql.jdbc.JDBC4PreparedStatement@fa9cf: SELECT * FROM test WHERE blah1='Hello' and blah2='World'

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

C# string replace

The simplest way is to do

line.Replace(@",", @";");

Output is shown as below:

enter image description here

How to sign in kubernetes dashboard?

All the previous answers are good to me. But a straight forward answer on my side would come from https://github.com/kubernetes/dashboard/wiki/Creating-sample-user#bearer-token. Just use kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}'). You will have many values for some keys (Name, Namespace, Labels, ..., token). The most important is the token that corresponds to your name. copy that token and paste it in the token box. Hope this helps.

The page cannot be displayed because an internal server error has occurred on server

For those of you who hit this stackoverflow entry because it ranks high for the phrase:

The page cannot be displayed because an internal server error has occurred.

In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.

Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.

Hide HTML element by id

<style type="text/css">
  #nav-ask{ display:none; }
</style>

Postgres ERROR: could not open file for reading: Permission denied

COPY your table (Name, Latitude, Longitude) FROM 'C:\Temp\your file.csv' DELIMITERS ',' CSV HEADER;

Use c:\Temp\"Your File"\.

PSEXEC, access denied errors

I still use psexec, even on win 10. Replace the psexec.exe in the Windows 10's win32 folder with the older version to work -> I use version 2.11.0.0. The Windows 10 version I was using would only run .bat files as background/hidden process on the remote computer. Took a whole day to figure this out.

Adding the registry key from above to the remote computer helps as well:

   reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

Why is the Android emulator so slow? How can we speed up the Android emulator?

Try reducing screen size, and maybe you should consider using Ubuntu. I've had the same issue, and somehow my emulator on the same PC works five times faster when using Linux.

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

Retrieving the last record in each group - MySQL

An approach with considerable speed is as follows.

SELECT * 
FROM messages a
WHERE Id = (SELECT MAX(Id) FROM messages WHERE a.Name = Name)

Result

Id  Name    Other_Columns
3   A   A_data_3
5   B   B_data_2
6   C   C_data_1

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

The issue I was facing was I have a project that is dependent on a library project. In order to build I was following these steps:

msbuild.exe myproject.vbproj /T:Rebuild
msbuild.exe myproject.vbproj /T:Package

That of course meant I was missing my library's dll files in bin and most importantly in the package zip file. I found this works perfectly:

msbuild.exe myproject.vbproj /T:Rebuild;Package

I have no idea why this work or why it didn't in the first place. But hope that helps.

In C#, why is String a reference type that behaves like a value type?

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

JavaScript and Threads

In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.

Extracting numbers from vectors of strings

We can also use str_extract from stringr

years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20  1

If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all which unlike str_extract returns all the macthes.

years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20"  "1"

stringr::str_extract_all(years, "\\d+")

#[[1]]
#[1] "20" "21"

#[[2]]
#[1] "1"

Java maximum memory on Windows XP

Everyone seems to be answering about contiguous memory, but have neglected to acknowledge a more pressing issue.

Even with 100% contiguous memory allocation, you can't have a 2 GiB heap size on a 32-bit Windows OS (*by default). This is because 32-bit Windows processes cannot address more than 2 GiB of space.

The Java process will contain perm gen (pre Java 8), stack size per thread, JVM / library overhead (which pretty much increases with each build) all in addition to the heap.

Furthermore, JVM flags and their default values change between versions. Just run the following and you'll get some idea:

 java -XX:+PrintFlagsFinal

Lots of the options affect memory division in and out of the heap. Leaving you with more or less of that 2 GiB to play with...

To reuse portions of this answer of mine (about Tomcat, but applies to any Java process):

The Windows OS limits the memory allocation of a 32-bit process to 2 GiB in total (by default).

[You will only be able] to allocate around 1.5 GiB heap space because there is also other memory allocated to the process (the JVM / library overhead, perm gen space etc.).

Why does 32-bit Windows impose a 2 GB process address space limit, but 64-bit Windows impose a 4GB limit?

Other modern operating systems [cough Linux] allow 32-bit processes to use all (or most) of the 4 GiB addressable space.

That said, 64-bit Windows OS's can be configured to increase the limit of 32-bit processes to 4 GiB (3 GiB on 32-bit):

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx

C# - How to convert string to char?

char[] myChar = theString.ToCharArray();

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

Get selected value in dropdown list using JavaScript

To go along with the previous answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)

let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text

In some rare instances you may need to use parentheses, but this would be very rare.

let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;

I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.

Unfortunately this still fetches the element twice, which is not ideal. A method that only grabs the element once would be more useful, but I have not figured that out yet, in regards to doing this with one line of code.

IN vs OR in the SQL WHERE Clause

I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN clearly wins)

Sharing a variable between multiple different threads

You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".

Please refer the below the code :

public class EvenOdd {

    static int a = 0;

    public static void main(String[] args) {

        EvenOdd eo = new EvenOdd();

        A aobj = eo.new A();
        B bobj = eo.new B();

        aobj.a = Lock.lock1;
        aobj.b = Lock.lock2;

        bobj.a = Lock.lock2;
        bobj.b = Lock.lock1;

        Thread t1 = new Thread(aobj);
        Thread t2 = new Thread(bobj);

        t1.start();
        t2.start();
    }

    static class Lock {
        final static Object lock1 = new Object();
        final static Object lock2 = new Object();
    }

    class A implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {
                try {
                    System.out.println(++EvenOdd.a + " A ");
                    synchronized (a) {
                        a.notify();
                    }
                    synchronized (b) {
                        b.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class B implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {

                try {
                    synchronized (b) {
                        b.wait();
                        System.out.println(++EvenOdd.a + " B ");
                    }
                    synchronized (a) {
                        a.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

OUTPUT :

1 A 
2 B 
3 A 
4 B 
5 A 
6 B 
7 A 
8 B 
9 A 
10 B 

Remove directory which is not empty

If you are using node 8+ want asyncronicity and don't want external dependencies, here is the async/await version:

const path = require('path');
const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const lstat = util.promisify(fs.lstat);
const unlink = util.promisify(fs.unlink);
const rmdir = util.promisify(fs.rmdir);

const removeDir = async (dir) => {
    try {
        const files = await readdir(dir);
        await Promise.all(files.map(async (file) => {
            try {
                const p = path.join(dir, file);
                const stat = await lstat(p);
                if (stat.isDirectory()) {
                    await removeDir(p);
                } else {
                    await unlink(p);
                    console.log(`Removed file ${p}`);
                }
            } catch (err) {
                console.error(err);
            }
        }))
        await rmdir(dir);
        console.log(`Removed dir ${dir}`);
    } catch (err) {
      console.error(err);
    }
}

How to find index of list item in Swift?

In Swift 2 (with Xcode 7), Array includes an indexOf method provided by the CollectionType protocol. (Actually, two indexOf methods—one that uses equality to match an argument, and another that uses a closure.)

Prior to Swift 2, there wasn't a way for generic types like collections to provide methods for the concrete types derived from them (like arrays). So, in Swift 1.x, "index of" is a global function... And it got renamed, too, so in Swift 1.x, that global function is called find.

It's also possible (but not necessary) to use the indexOfObject method from NSArray... or any of the other, more sophisticated search meth dis from Foundation that don't have equivalents in the Swift standard library. Just import Foundation (or another module that transitively imports Foundation), cast your Array to NSArray, and you can use the many search methods on NSArray.

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

Check input value length

<input type='text' minlength=3 /><br />

if browser supports html5,

it will automatical be validate attributes(minlength) in tag

but Safari(iOS) doesn't working

How do I get my solution in Visual Studio back online in TFS?

I am using Visual Studio 2017 15.4.0 version. Especially when i started use lightweight solution option, this offline thing happened to me. I tried to above solutions which are:

  1. Tried to regedit option but can not see appropriate menu options. Didn't work.
  2. Right click on solution, there is go online option and when i choose it that gives this error message: "The solution is offline because its associated Team Foundation Server is offline. Unable to determine the workspace for this solution."

Then from File -> Source Control -> Advanced -> Change Source Control. I saw my files. I select them and then chose bind option. That worked for me.

Auto logout with Angularjs based on idle user

You could also accomplish using angular-activity-monitor in a more straight forward way than injecting multiple providers and it uses setInterval() (vs. angular's $interval) to avoid manually triggering a digest loop (which is important to prevent keeping items alive unintentionally).

Ultimately, you just subscribe to a few events that determine when a user is inactive or becoming close. So if you wanted to log out a user after 10 minutes of inactivity, you could use the following snippet:

angular.module('myModule', ['ActivityMonitor']);

MyController.$inject = ['ActivityMonitor'];
function MyController(ActivityMonitor) {
  // how long (in seconds) until user is considered inactive
  ActivityMonitor.options.inactive = 600;

  ActivityMonitor.on('inactive', function() {
    // user is considered inactive, logout etc.
  });

  ActivityMonitor.on('keepAlive', function() {
    // items to keep alive in the background while user is active
  });

  ActivityMonitor.on('warning', function() {
    // alert user when they're nearing inactivity
  });
}

How do I increase the capacity of the Eclipse output console?

Under Window > Preferences, go to the Run/Debug > Console section, then you should see an option "Limit console output." You can unchecked this or change the number in the "Console buffer size (characters)" text box below. Do Unchecked.

This is for the Eclipse like Galileo, Kepler, Juno, Luna, Mars and Helios.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

What should be in my .gitignore for an Android Studio project?

In the case of Android Studio, the only files that are required to be saved in version control are the files required to build the application from the command line using gradle. So you can ignore:

  • *.iml
  • .idea
  • build

However, if you save any IDE settings, such as custom code style settings, they get saved in the .idea folder. If you want those changes in version control, then you'd save the IDEA files as well (*.iml and .idea).

Jquery Validate custom error message location

Add this code in your validate method:

 errorLabelContainer: '#errors'

and in your html, put simply this where you want to catch the error:

<div id="errors"></div>

All the errors will be held in the div, independently of your input box.

It worked very fine for me.

How do I subscribe to all topics of a MQTT broker

Subscribing to # gives you a subscription to everything except for topics that start with a $ (these are normally control topics anyway).

It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to # explicitly.

Disable browser's back button

You should be using posts with proper expires and caching headers.

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

How can I write text on a HTML5 canvas element?

It is easy to write text to a canvas. Lets say that you canvas is declared like below.

<html>
  <canvas id="YourCanvas" width="500" height="500">
   Your Internet Browser does not support HTML5 (Get a new Browser)
  </canvas>
</html>

This part of the code returns a variable into canvas which is a representation of your canvas in HTML.

  var c  = document.getElementById("YourCanvas");

The following code returns the methods for drawing lines, text, fills to your canvas.

  var ctx = canvas.getContext("2d");

<script>
  ctx.font="20px Times Roman";
  ctx.fillText("Hello World!",50,100);

  ctx.font="30px Verdana";

  var g = ctx.createLinearGradient(0,0,c.width,0);

  g.addColorStop("0","magenta");
  g.addColorStop("0.3","blue");
  g.addColorStop("1.0","red");

  ctx.fillStyle=g; //Sets the fille of your text here. In this case it is set to the gradient that was created above. But you could set it to Red, Green, Blue or whatever.

  ctx.fillText("This is some new and funny TEXT!",40,190);
</script>

There is a beginners guide out on Amazon for the kindle http://www.amazon.com/HTML5-Canvas-Guide-Beginners-ebook/dp/B00JSFVY9O/ref=sr_1_4?ie=UTF8&qid=1398113376&sr=8-4&keywords=html5+canvas+beginners that is well worth the money. I purchased it a couple of days ago and it showed me a lot of simple techniques that were very useful.

Getting a union of two arrays in JavaScript

ES2015 version

Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)};

Array.prototype.union = function(a) {return [...this.diff(a), ...a]}

Check if two lists are equal

List<T> equality does not check them element-by-element. You can use LINQ's SequenceEqual method for that:

var a = ints1.SequenceEqual(ints2);

To ignore order, use SetEquals:

var a = new HashSet<int>(ints1).SetEquals(ints2);

This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:

var counts = ints1
    .GroupBy(v => v)
    .ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
    int c;
    if (counts.TryGetValue(n, out c)) {
        counts[n] = c-1;
    } else {
        ok = false;
        break;
    }
}
var res = ok && counts.Values.All(c => c == 0);

Finally, if you are fine with an O(N*LogN) solution, you can sort the two sequences, and compare them for equality using SequenceEqual.

How to execute UNION without sorting? (SQL)

Try this:

  SELECT DISTINCT * FROM (

      SELECT  column1, column2 FROM Table1
      UNION ALL
      SELECT  column1, column2 FROM Table2
      UNION ALL
      SELECT  column1, column2 FROM Table3

  ) X ORDER BY Column1

Import Google Play Services library in Android Studio

I got the same problem. I just tried to rebuild, clean and restart but no luck. Then I just remove

compile 'com.google.android.gms:play-services:8.3.0'

from build.gradle and resync. After that I put it again and resync. Next to that, I clean the project and the problem is gone!!

I hope it will help any of you facing the same.

How to do a https request with bad certificate?

All of these answers are wrong! Do not use InsecureSkipVerify to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName on tls.Config. If tls.Config.ServerName == remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.

There is one legitimate use for InsecureSkipVerify: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify, it's generally because you didn't set ServerName properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).

In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify, or you will learn what is wrong with it the hard way!

Find IP address of directly connected device

You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:

http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html

LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).

You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.

Impersonate tag in Web.Config

Put the identity element before the authentication element

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

In SSMS 2012, you'll have to use:

To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.

  1. Add "-m;" into parameters;
  2. Restart the service and logon this SQL instance by using windows authentication;
  3. The rest steps are same as above. Change your windows user account permission in security or reset SA account password.
  4. Last, remove "-m" parameter from "startup parameters";

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Select distinct values from a large DataTable column

Sorry to post answer for very old thread. my answer may help other in future.

string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

    //Following function will return Distinct records for Name, City and State column.
    public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
       {
           DataTable dtUniqRecords = new DataTable();
           dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
           return dtUniqRecords;
       }

How to send a “multipart/form-data” POST in Android with Volley

Complete Multipart Request with Upload Progress

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.beusoft.app.AppContext;

public class MultipartRequest extends Request<String> {

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    HttpEntity httpentity;
    private String FILE_PART_NAME = "files";

    private final Response.Listener<String> mListener;
    private final File mFilePart;
    private final Map<String, String> mStringPart;
    private Map<String, String> headerParams;
    private final MultipartProgressListener multipartProgressListener;
    private long fileLength = 0L;

    public MultipartRequest(String url, Response.ErrorListener errorListener,
            Response.Listener<String> listener, File file, long fileLength,
            Map<String, String> mStringPart,
            final Map<String, String> headerParams, String partName,
            MultipartProgressListener progLitener) {
        super(Method.POST, url, errorListener);

        this.mListener = listener;
        this.mFilePart = file;
        this.fileLength = fileLength;
        this.mStringPart = mStringPart;
        this.headerParams = headerParams;
        this.FILE_PART_NAME = partName;
        this.multipartProgressListener = progLitener;

        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            entity.setCharset(CharsetUtils.get("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        buildMultipartEntity();
        httpentity = entity.build();
    }

    // public void addStringBody(String param, String value) {
    // if (mStringPart != null) {
    // mStringPart.put(param, value);
    // }
    // }

    private void buildMultipartEntity() {
        entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
        if (mStringPart != null) {
            for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
                entity.addTextBody(entry.getKey(), entry.getValue());
            }
        }
    }

    @Override
    public String getBodyContentType() {
        return httpentity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            httpentity.writeTo(new CountingOutputStream(bos, fileLength,
                    multipartProgressListener));
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {

        try {
//          System.out.println("Network Response "+ new String(response.data, "UTF-8"));
            return Response.success(new String(response.data, "UTF-8"),
                    getCacheEntry());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            // fuck it, it should never happen though
            return Response.success(new String(response.data), getCacheEntry());
        }
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

//Override getHeaders() if you want to put anything in header

    public static interface MultipartProgressListener {
        void transferred(long transfered, int progress);
    }

    public static class CountingOutputStream extends FilterOutputStream {
        private final MultipartProgressListener progListener;
        private long transferred;
        private long fileLength;

        public CountingOutputStream(final OutputStream out, long fileLength,
                final MultipartProgressListener listener) {
            super(out);
            this.fileLength = fileLength;
            this.progListener = listener;
            this.transferred = 0;
        }

        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            if (progListener != null) {
                this.transferred += len;
                int prog = (int) (transferred * 100 / fileLength);
                this.progListener.transferred(this.transferred, prog);
            }
        }

        public void write(int b) throws IOException {
            out.write(b);
            if (progListener != null) {
                this.transferred++;
                int prog = (int) (transferred * 100 / fileLength);
                this.progListener.transferred(this.transferred, prog);
            }
        }

    }
}

Sample Usage

protected <T> void uploadFile(final String tag, final String url,
            final File file, final String partName,         
            final Map<String, String> headerParams,
            final Response.Listener<String> resultDelivery,
            final Response.ErrorListener errorListener,
            MultipartProgressListener progListener) {
        AZNetworkRetryPolicy retryPolicy = new AZNetworkRetryPolicy();

        MultipartRequest mr = new MultipartRequest(url, errorListener,
                resultDelivery, file, file.length(), null, headerParams,
                partName, progListener);

        mr.setRetryPolicy(retryPolicy);
        mr.setTag(tag);

        Volley.newRequestQueue(this).add(mr);

    }

xcopy file, rename, suppress "Does xxx specify a file name..." message

xcopy src dest /I

REM This assumes dest is a folder and will create it, if it doesnt exists

SQL SELECT from multiple tables

SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product AS p
    LEFT JOIN customer1 AS c1
        ON p.cid = c1.cid
    LEFT JOIN customer2 AS c2
        ON p.cid = c2.cid

How to split a file into equal parts, without breaking individual lines?

The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log. The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...

wc -l on the original file and output gives:

  321 auth.log
   75 auth.log.aa
   75 auth.log.ab
   75 auth.log.ac
   75 auth.log.ad
   21 auth.log.ae
  642 total

Debugging JavaScript in IE7

Microsoft Script Editor is indeed an option, and of the ones I've tried one of the more stable ones -- the debugger in IE8 is great but for some reason whenever I start the Developer Tools it takes IE8 a while, sometimes up to a minute, to inspect my page's DOM tree. And afterwards it seems to want to do it on every page refresh which is a torture.

You can inspect contents of variables in Microsoft Script editor: if you poke around under Debug > Window you can turn on local variable inspection, watching etc.

The other option, Visual Web Dev, while bulky, works reasonably well. To set it up, do this (stolen from here):

  1. Debugging should be turned on in IE. Go into Tools > Internet Options > Advanced and check that Disable Script Debugging (Internet Explorer) is unchecked and Display a notification about every script error is checked
  2. Create a new empty web project inside of VWD
  3. Right-click on the site in the Solutions Explorer on the top right, go to Browse With and make sure your default browser is set to IE (it's reasonable to assume if you're a web developer IE is not your default browser in which case that won't be the default.. by default)
  4. Hit F5, IE will open up. Browse to the page you want to debug.
  5. VWD will now open up any time you have a script error or if you set a breakpoint in one of the JS files. Debug away!

UPDATE: By the way, if you experience the same slowdowns as me with IE8's otherwise decent debugger, there is a workaround -- if you encounter or make IE encounter an error so that it pops up the "Do you want to debug" dialogue and hit Yes, the debugger will come up pretty much instantly. It seems like if you go "straight" into debugging mode the Dev Tools never inspect the DOM. It's only when you hit F12 that it does.

Difference Between ViewResult() and ActionResult()

To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx

ActionResult is an abstract class, and it's base class for ViewResult class.

In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.

And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.

It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.

How can I add a variable to console.log?

You can also use printf style of formatting arguments. It is available in at least Chrome, Firefox/Firebug and node.js.

var name = prompt("what is your name?");

console.log("story %s story", name);

It also supports %d for formatting numbers

Can't import javax.servlet.annotation.WebServlet

If you're using Maven and don't want to link Tomcat in the Targeted Runtimes in Eclipse, you can simply add the dependency with scope provided in your pom.xml:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

iOS - UIImageView - how to handle UIImage image orientation

You can completely avoid manually doing the transforms and scaling yourself, as suggested by an0 in this answer here:

- (UIImage *)normalizedImage {
    if (self.imageOrientation == UIImageOrientationUp) return self; 

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

The documentation for the UIImage methods size and drawInRect explicitly states that they take into account orientation.

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

How to compare if two structs, slices or maps are equal?

If you're comparing them in unit test, a handy alternative is EqualValues function in testify.

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

Remove characters from C# string

Sounds like an ideal application for RegEx -- an engine designed for fast text manipulation. In this case:

Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

String Concatenation in EL

it also can be a great idea using concat for EL + MAP + JSON problem like in this example :

#{myMap[''.concat(myid)].content}

Change Tomcat Server's timeout in Eclipse

Windows->Preferences->Server

Server Timeout can be specified there.

or another method via the Servers tab here:

http://henneberke.wordpress.com/2009/09/28/fixing-eclipse-tomcat-timeout/

How to show matplotlib plots in python

plt.plot(X,y) function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show() after plt.plot(X,y). So,

import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

How to return a part of an array in Ruby?

You can use slice() for this:

>> foo = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> bar = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> half = foo.length / 2
=> 3
>> foobar = foo.slice(0, half) + bar.slice(half, foo.length)
=> [1, 2, 3, 40, 50, 60]

By the way, to the best of my knowledge, Python "lists" are just efficiently implemented dynamically growing arrays. Insertion at the beginning is in O(n), insertion at the end is amortized O(1), random access is O(1).

No connection string named 'MyEntities' could be found in the application config file

It also happens if the startup project is changed to the one, which does not have the connection strings.

  1. Right Click Solution - click properties
  2. Under Common Properties,select startup project
  3. On the right pane select the project which has the connection strings (in most cases, it will be MVC projects - the project that starts the solution)

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

How to set the matplotlib figure default size in ipython notebook?

Worked liked a charm for me:

matplotlib.rcParams['figure.figsize'] = (20, 10)

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

How to check if internet connection is present in Java?

The following piece of code allows us to get the status of the network on our Android device

public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            TextView mtv=findViewById(R.id.textv);
            ConnectivityManager connectivityManager=
                  (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if(((Network)connectivityManager.getActiveNetwork())!=null)
                    mtv.setText("true");
                else
                    mtv.setText("fasle");
            }
        }
    }

How to add image in Flutter

To use image in Flutter. Do these steps.

1. Create a Directory inside assets folder named images. As shown in figure belowenter image description here

2. Put your desired images to images folder.

3. Open pubpsec.yaml file . And add declare your images.Like:--enter image description here

4. Use this images in your code as.

  Card(
            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          ),
          ),
          child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
                alignment: Alignment.center,
          ),
          );

How do I add an active class to a Link from React Router?

You can actually replicate what is inside NavLink something like this

const NavLink = ( {
  to,
  exact,
  children
} ) => {

  const navLink = ({match}) => {

    return (
      <li class={{active: match}}>
        <Link to={to}>
          {children}
        </Link>
      </li>
    )

  }

  return (
    <Route
      path={typeof to === 'object' ? to.pathname : to}
      exact={exact}
      strict={false}
      children={navLink}
    />
  )
}

just look into NavLink source code and remove parts you don't need ;)

How to convert int to float in python?

Other than John's answer, you could also make one of the variable float, and the result will yield float.

>>> 144 / 314.0
0.4585987261146497

Upload files with HTTPWebrequest (multipart/form-data)

I realize this is probably really late, but I was searching for the same solution. I found the following response from a Microsoft rep

private void UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
{

    long length = 0;
    string boundary = "----------------------------" +
    DateTime.Now.Ticks.ToString("x");


    HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
    boundary;
    httpWebRequest2.Method = "POST";
    httpWebRequest2.KeepAlive = true;
    httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;



    Stream memStream = new System.IO.MemoryStream();
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


    string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

    foreach(string key in nvc.Keys)
    {
        string formitem = string.Format(formdataTemplate, key, nvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        memStream.Write(formitembytes, 0, formitembytes.Length);
    }


    memStream.Write(boundarybytes,0,boundarybytes.Length);

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

    for(int i=0;i<files.Length;i++)
    {

        string header = string.Format(headerTemplate,"file"+i,files[i]);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        memStream.Write(headerbytes,0,headerbytes.Length);


        FileStream fileStream = new FileStream(files[i], FileMode.Open,
        FileAccess.Read);
        byte[] buffer = new byte[1024];

        int bytesRead = 0;

        while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
        {
            memStream.Write(buffer, 0, bytesRead);
        }


        memStream.Write(boundarybytes,0,boundarybytes.Length);


        fileStream.Close();
    }

    httpWebRequest2.ContentLength = memStream.Length;
    Stream requestStream = httpWebRequest2.GetRequestStream();

    memStream.Position = 0;
    byte[] tempBuffer = new byte[memStream.Length];
    memStream.Read(tempBuffer,0,tempBuffer.Length);
    memStream.Close();
    requestStream.Write(tempBuffer,0,tempBuffer.Length );
    requestStream.Close();


    WebResponse webResponse2 = httpWebRequest2.GetResponse();

    Stream stream2 = webResponse2.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);

    webResponse2.Close();
    httpWebRequest2 = null;
    webResponse2 = null;

}

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

Oracle error : ORA-00905: Missing keyword

Unless there is a single row in the ASSIGNMENT table and ASSIGNMENT_20081120 is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE, this is not what you want.

Assuming you are trying to create a new table and copy the existing data to that new table

CREATE TABLE assignment_20081120
AS
SELECT *
  FROM assignment

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Change values of select box of "show 10 entries" of jquery datatable

enter image description here pageLength: 50,

worked for me Thanks

Versions for reference

jquery-3.3.1.js

/1.10.19/js/jquery.dataTables.min.js

/buttons/1.5.2/js/dataTables.buttons.min.js

Use of String.Format in JavaScript?

Here is a useful string formatting function using regular expressions and captures:

function format (fmtstr) {
  var args = Array.prototype.slice.call(arguments, 1);
  return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
    return args[index];
  });
}

Strings can be formatted like C# String.Format:

var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"

the format will place the correct variable in the correct spot, even if they appear out of order:

var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"

Hope this helps!

ArrayList or List declaration in Java

Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach

List<String> strings = new ArrayList<String>();

because it's hide the implementation detail from user. You precisely

List<String> strings = new ArrayList<String>(); 

it's generic approach and this specialized approach

ArrayList<String> strings = new ArrayList<String>();

For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

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).

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Then NumPy sum function takes an optional axis argument that specifies along which axis you would like the sum performed:

>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])

Or, equivalently:

>>> numpy.sum(a, 0)
array([18, 22, 26])

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

How do I change the background color with JavaScript?

Or...you can just do background(0);, in function draw(); (0 is the color black)

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

It looks that even if the driver 10.2 is compatible with the JDBC3 it may not work with JRE6 as I've found here:

http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_03

Which JDBC drivers support which versions of Javasoft's JDK?

pre-8i OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.5 OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.6SDK THIN Driver - JDK 1.1.x and JDK 1.2.x (aka Java2)
8.1.6SDK OCI Driver - Only JDK 1.1.x
8.1.6 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
8.1.7 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
9.0.1 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x and JDK 1.3.x
9.2.0 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.1.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.2.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, JDK 1.4.x, and JDK 5.0.x
11.1.0 OCI and THIN Driver - JDK 1.5.x and JDK 1.6.x

Oracle 10.2.0 supports:

Full support for JDBC 3.0
Note that there is no real change in the support for the following in the database. Allthat has changed is that some methods that previously threw SQLException now do something more reasonable instead.
result-set holdability
returning multiple result-sets.

How to make a HTTP request using Ruby on Rails?

require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')

How to horizontally center an element

You can apply this CSS to the inner <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

Working example here:

_x000D_
_x000D_
#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


EDIT

With flexbox it is very easy to style the div horizontally and vertically centered.

_x000D_
_x000D_
#inner {  
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%;
  display: flex;
  justify-content: center;
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_

To align the div vertically centered, use the property align-items: center.

Array formula on Excel for Mac

This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.

Which mime type should I use for mp3

I had a problem with mime types and where making tests for few file types. It looks like each browser sends it's variation of a mime type for a specific file. I was trying to upload mp3 and zip files with open source php class, that what I have found:

  • Firefox (mp3): audio/mpeg
  • Firefox (zip): application/zip
  • Chrome (mp3): audio/mp3
  • Chrome (zip): application/octet-stream
  • Opera (mp3): audio/mp3
  • Opera (zip): application/octet-stream
  • IE (mp3): audio/mpeg
  • IE (zip): application/x-zip-compressed

So if you need several file types to upload, you better make some tests so that every browser could upload a file and pass mime type check.

nvm keeps "forgetting" node in new terminal session

To install the latest stable version:

nvm install stable

To set default to the stable version (instead of a specific version):

nvm alias default stable

To list installed versions:

nvm list

As of v6.2.0, it will look something like:

$ nvm list
         v4.4.2
->       v6.2.0
default -> stable (-> v6.2.0)
node -> stable (-> v6.2.0) (default)
stable -> 6.2 (-> v6.2.0) (default)
iojs -> N/A (default)

Do a "git export" (like "svn export")?

Probably the simplest way to achieve this is with git archive. If you really need just the expanded tree you can do something like this.

git archive master | tar -x -C /somewhere/else

Most of the time that I need to 'export' something from git, I want a compressed archive in any case so I do something like this.

git archive master | bzip2 >source-tree.tar.bz2

ZIP archive:

git archive --format zip --output /full/path/to/zipfile.zip master 

git help archive for more details, it's quite flexible.


Be aware that even though the archive will not contain the .git directory, it will, however, contain other hidden git-specific files like .gitignore, .gitattributes, etc. If you don't want them in the archive, make sure you use the export-ignore attribute in a .gitattributes file and commit this before doing your archive. Read more...


Note: If you are interested in exporting the index, the command is

git checkout-index -a -f --prefix=/destination/path/

(See Greg's answer for more details)

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Jaqen H'ghar is spot-on. A third way is to:

  1. Go to Manage NuGet Packages
  2. Install Microsoft.jQuery.Unobtrusive.Validation
  3. Open Global.asax.cs file and add this code inside the Application_Start method

Code that runs on application startup:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
    Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
    DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});

How do I get the entity that represents the current user in Symfony2?

The thread is a bit old but i think this could probably save someone's time ...

I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

It eventually turned out that i was logged in using an in memory user

my security.yml looks something like this

security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, fos_userbundle]
        fos_userbundle:
            id: fos_user.user_manager
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }

the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

Thanks, hj

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

How can I symlink a file in Linux?

ln [-Ffhinsv] source_file [target_file]

    link, ln -- make links

        -s    Create a symbolic link.

    A symbolic link contains the name of the file to which it is linked. 

    An ln command appeared in Version 1 AT&T UNIX.

Angular 5 ngHide ngShow [hidden] not working

If you want to just toggle visibility and still keep the input in DOM:

<input class="txt" type="password" [(ngModel)]="input_pw" 
 [style.visibility]="isHidden? 'hidden': 'visible'">

The other way around is as per answer by rrd, which is to use HTML hidden attribute. In an HTML element if hidden attribute is set to true browsers are supposed to hide the element from display, but the problem is that this behavior is overridden if the element has an explicit display style mentioned.

_x000D_
_x000D_
.hasDisplay {_x000D_
  display: block;_x000D_
}
_x000D_
<input class="hasDisplay" hidden value="shown" />_x000D_
<input hidden value="not shown">
_x000D_
_x000D_
_x000D_

To overcome this you can opt to use an explicit css for [hidden] that overrides the display;

[hidden] {
  display: none !important;
}

Yet another way is to have a is-hidden class and do:

<input [class.is-hidden]="isHidden"/>

.is-hidden {
      display: none;
 }

If you use display: none the element will be skipped from the static flow and no space will be allocated for the element, if you use visibility: hidden it will be included in the flow and a space will be allocated but it will be blank space.

The important thing is to use one way across an application rather than mixing different ways thereby making the code less maintainable.

If you want to remove it from DOM

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

Push method in React Hooks (useState)?

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

How can I confirm a database is Oracle & what version it is using SQL?

If your instance is down, you are look for version information in alert.log

Or another crude way is to look into Oracle binary, If DB in hosted on Linux, try strings on Oracle binary.

strings -a $ORACLE_HOME/bin/oracle |grep RDBMS | grep RELEASE

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

In my case (where none of the proposed solutions fit), the problem was I used async/await where the signature for main method looked this way:

static async void Main(string[] args)

I simply removed async so the main method looked this way:

static void Main(string[] args)

I also removed all instances of await and used .Result for async calls, so my console application could compile happily.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.

Patch

Override and reset CSS style: auto or none don't work

The best way that I've found to revert a min-width setting is:

min-width: 0;
min-width: unset;

unset is in the spec, but some browsers (IE 10) do not respect it, so 0 is a good fallback in most cases. min-width: 0;

How to "grep" for a filename instead of the contents of a file?

Also for multiple files.

tree /path/to/directory/ | grep -i "file1 \| file2 \| file3"

z-index not working with position absolute

The second div is position: static (the default) so the z-index does not apply to it.

You need to position (set the position property to anything other than static, you probably want relative in this case) anything you want to give a z-index to.

Inserting a value into all possible locations in a list

Simplest is use list[i:i]

    a = [1,2, 3, 4]
    a[2:2] = [10]

Print a to check insertion

    print a
    [1, 2, 10, 3, 4]

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The problem lays here:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id

In order to use union or union all number of columns and their types should be identical cross all result sets.

I guess you should just add the column LOC_deelVan_LOC_id to your second result set

Remove all occurrences of char from string

I like using RegEx in this occasion:

str = str.replace(/X/g, '');

where g means global so it will go through your whole string and replace all X with ''; if you want to replace both X and x, you simply say:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

ORA-28001: The password has expired

I had same problem even after changing the password, it wasn't getting reflected in SQLDEVELOPER.

Atlast following solved my problem :

  1. Open Command Propmt
  2. Type sqlplus
  3. login as sysdba
  4. Run following command : alter user USERNAME identified by NEW_PASSWORD;

AngularJS format JSON string output

In addition to the angular json filter already mentioned, there is also the angular toJson() function.

angular.toJson(obj, pretty);

The second param of this function lets you switch on pretty printing and set the number of spaces to use.

If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

How to remove a file from the index in git?

git reset HEAD <file> 

for removing a particular file from the index.

and

git reset HEAD

for removing all indexed files.

Setting public class variables

Add getter and setter method to your class.

public function setValue($new_value)
{
    $this->testvar = $new_value;
}

public function getValue()
{
    return $this->testvar;        
}

Password must have at least one non-alpha character

I tried Omega's example however it was not working with my C# code. I recommend using this instead:

[RegularExpression(@"^(?=[^\d_].*?\d)\w(\w|[!@#$%]){7,20}", ErrorMessage = @"Error. Password must have one capital, one special character and one numerical character. It can not start with a special character or a digit.")]

Submitting form and pass data to controller method of type FileStreamResult

You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get to FormMethod.Post.

As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

Getting a list of files in a directory with a glob

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end

Difference between int32, int, int32_t, int8 and int8_t

The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.

Change user-agent for Selenium web-driver

To build on Louis's helpful answer...

Setting the User Agent in PhantomJS

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)

The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:

driver.execute_script("return navigator.userAgent")

So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.

How to set cursor to input box in Javascript?

You have not provided enough code to help You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.

Here is the canonical plain javascript method of validating a form It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point DEMO

function validate(formObj) {
  document.getElementById("errorMsg").innerHTML = "";    
  var quantity = formObj.quantity;
  if (isNaN(quantity)) {
    quantity.value="";
    quantity.focus();
    document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
    return false;
  }
  return true; // allow submit
}   

Here is the HTML

<form onsubmit="return validate(this)">
    <input type="text" name="quantity" value="" />
    <input type="submit" />
</form>    
<span id="errorMsg"></span>

node.js: cannot find module 'request'

I tried installing the module locally with version and it worked!!

npm install request@^2.*

Thanks.

How do you make strings "XML safe"?

If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

What are the differences between delegates and events?

An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

before start make sure of installation:

yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
  1. start xming or cygwin
  2. make connection with X11 forwarding (in putty don't forget to set localhost:0.0 for X display location)
  3. edit sshd.cong and restart
     cat /etc/ssh/sshd_config | grep X
                             X11Forwarding yes
                             X11DisplayOffset 10
AddressFamily inet
  1. Without the X11 forwarding, you are subjected to the X11 SECURITY and then you must: authorize the remote server to make a connection with the local X Server using a method (for instance, the xhost command) set the display environment variable to redirect the output to the X server of your local computer. In this example: 192.168.2.223 is the IP of the server 192.168.2.2 is the IP of the local computer where the x server is installed. localhost can also be used.
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list

blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&

Then the xclock application must launch.

Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

Can try with below code

 WebDriverWait wait = new WebDriverWait(driver, 30);

Pass other element would receive the click:<a class="navbar-brand" href="#"></a>

    boolean invisiable = wait.until(ExpectedConditions
            .invisibilityOfElementLocated(By.xpath("//div[@class='navbar-brand']")));

Pass clickable button id as shown below

    if (invisiable) {
        WebElement ele = driver.findElement(By.xpath("//div[@id='button']");
        ele.click();
    }

Given a starting and ending indices, how can I copy part of a string in C?

Have you checked strncpy?

char * strncpy ( char * destination, const char * source, size_t num );

You must realize that begin and end actually defines a num of bytes to be copied from one place to another.

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

Secure hash and salt for PHP passwords

I would not store the password hashed in two different ways, because then the system is at least as weak as the weakest of the hash algorithms in use.

Bootstrap combining rows (rowspan)

Note: This was for Bootstrap 2 (relevant when the question was asked).

You can accomplish this by using row-fluid to make a fluid (percentage) based row inside an existing block.

<div class="row">
   <div class="span5">span5</div>
   <div class="span3">span3</div>
   <div class="span2">
      <div class="row-fluid">
         <div class="span12">span2</div>
         <div class="span12">span2</div>
      </div>
   </div>
   <div class="span2">span2</div>
</div>
<div class="row">
   <div class="span6">
      <div class="row-fluid">
         <div class="span12">span6</div>
         <div class="span12">span6</div>
      </div>
   </div>
   <div class="span6">span6</div>
</div>

Here's a JSFiddle example.

I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):

.row-fluid [class*="span"] {
    margin-left: 0;
}

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

And there's yet a third option. In your onCreate() method, find all the button views that you have and save them as class data members. You can then cascade a group of if-else statements to find which is which. It's kind of messy, but it's a must if you don't know the ID of the buttons (which can be complicated if you are generating buttons in java code).

@Override
public void onClick(View v) {
    if (v == m_myCards) {
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
    }
    else if (v == m_exit) {
        MyAlertDialog();
    }
    else if (v == m_back) {
        finish();            
    }

Another nice thing about this technique is that it's flexible and quick (no having to parse IDs). The bad thing is that you need to keep the widgets in memory.

Don't know which method is better.

Pandas: Creating DataFrame from Series

No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame() with the parens).

Instead, to create a DataFrame where each series is a column,

  1. make a list of Series, series, and
  2. concatenate them horizontally with df = pd.concat(series, axis=1)

Something like:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

What generates the "text file busy" message in Unix?

root@h1:bin[0]# mount h2:/ /x             
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat 
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#

ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok

How do I reload a page without a POSTDATA warning in Javascript?

To bypass POST warning you must reload page with full URL. Works fine.

window.location.href = window.location.protocol +'//'+ window.location.host + window.location.pathname;

What to gitignore from the .idea folder?

in my case /**/.idea/* works well

Difference in months between two dates

LINQ Solution,

DateTime ToDate = DateTime.Today;
DateTime FromDate = ToDate.Date.AddYears(-1).AddDays(1);

int monthCount = Enumerable.Range(0, 1 + ToDate.Subtract(FromDate).Days)
                    .Select(x => FromDate.AddDays(x))
                    .ToList<DateTime>()
                    .GroupBy(z => new { z.Year, z.Month })
                    .Count();

How to convert an OrderedDict into a regular dict in python3

Its simple way

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))

Testing pointers for validity (C/C++)

This article MEM10-C. Define and use a pointer validation function says it is possible to do a check to some degree, especially under Linux OS.

Troubleshooting misplaced .git directory (nothing to commit)

I have faced the same issue with git while working with angular CLI 6.1.2. Angular CLI 6.1.2 automatically initializes .git folder when you create a new angular project using Angular CLI. So when I tried git status - it was not detecting the whole working directory.

I have just deleted the hidden .git folder from my angular working directory and then initialized git repository again with git init. And now, I can see all my files with git status.