Programs & Examples On #Sparse array

CSS How to set div height 100% minus nPx

I haven't seen anything like this posted yet, but I thought I'd put it out there.

<div class="main">
<header>Header</header>
<div class="content">Content</div>

Then CSS:

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.main {
    height: 100%;
    padding-top: 50px;
    box-sizing: border-box;
}

header {
    height: 50px;
    margin-top: -50px;
    width: 100%;
    background-color: #5078a5;
}

.content {
    height: 100%;
    background-color: #999999;
}

Here is a working jsfiddle

Note: I have no idea what the browser compatability is for this. I was just playing around with alternate solutions and this seemed to work well.

How do I modify a MySQL column to allow NULL?

Use: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

Position of a string within a string using Linux shell script?

With bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%$2*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

How do I close an Android alertdialog

you can simply restart the activity where your alertdialog appear or another activity depend on your judgement. if you want to restart activity use this finish(); startActivity(getIntent());

XSLT equivalent for JSON

it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer.

Sample code in Java: http://www.gerixsoft.com/blog/json/xslt4json

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

i haved same problem when add new data in lazy image loader i just put

         adapter.notifyDataSetChanged();

in

       protected void onPostExecute(Void args) {
        adapter.notifyDataSetChanged();
        // Close the progressdialog
        mProgressDialog.dismiss();
         }

hope it helps you

Creating a div element in jQuery

Here's another technique for creating divs with jQuery.

ELEMENT CLONING

Say you have an existing div in your page that you want to clone using jQuery (e.g. to duplicate an input a number of times in a form). You would do so as follows.

_x000D_
_x000D_
$('#clone_button').click(function() {_x000D_
  $('#clone_wrapper div:first')_x000D_
  .clone()_x000D_
  .append('clone')_x000D_
  .appendTo($('#clone_wrapper'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="clone_wrapper">_x000D_
  <div>_x000D_
    Div_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<button id="clone_button">Clone me!</button>
_x000D_
_x000D_
_x000D_

header('HTTP/1.0 404 Not Found'); not doing anything

Use these codes for 404 not found.

if(strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  readfile('404missing.html');
  exit();
}

Here 404missing.html is your Not found design page. (it can be .html or .php)

bash string compare to multiple correct values

Instead of saying:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.

Extract specific columns from delimited file using Awk

You can use a for-loop to address a field with $i:

ls -l | awk '{for(i=3 ; i<8 ; i++) {printf("%s\t", $i)} print ""}'

Creating a textarea with auto-resize

A COMPLETE YET SIMPLE SOLUTION

Updated 2020-05-14 (Improved browser support for mobiles and tablets)

The following code will work:

  • On key input.
  • With pasted text (right click & ctrl+v).
  • With cut text (right click & ctrl+x).
  • With pre-loaded text.
  • With all textarea's (multiline textbox's) site wide.
  • With Firefox (v31-67 tested).
  • With Chrome (v37-74 tested).
  • With IE (v9-v11 tested).
  • With Edge (v14-v18 tested).
  • With IOS Safari.
  • With Android Browser.
  • With JavaScript strict mode.
  • Is w3c validated.
  • And is streamlined and efficient.

OPTION 1 (With jQuery)

This option requires jQuery and has been tested and is working with 1.7.2 - 3.3.1

Simple (Add this jquery code to your master script file and forget about it.)

_x000D_
_x000D_
$('textarea').each(function () {
  this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This javascript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>
_x000D_
_x000D_
_x000D_

Test on jsfiddle


OPTION 2 (Pure JavaScript)

Simple (Add this JavaScript to your master script file and forget about it.)

_x000D_
_x000D_
const tx = document.getElementsByTagName('textarea');
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
}
_x000D_
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>
_x000D_
_x000D_
_x000D_

Test on jsfiddle


OPTION 3 (jQuery Extension)

Useful if you want to apply further chaining to the textareas you want to be auto-sized.

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ 'height': 'auto', 'overflow-y': 'hidden' })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on('input', function() {
        autoHeight_(this);
      });
    });
  }
});

Invoke with $('textarea').autoHeight()


UPDATING TEXTAREA VIA JAVASCRIPT

When injecting content into a textarea via JavaScript append the following code to invoke the function in option 1.

$('textarea').trigger('input');

PRESET TEXTAREA HEIGHT

To fix the initial height of the textarea you will need to add an additional condition:

_x000D_
_x000D_
const txHeight = 16;
const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  if (tx[i].value == '') {
    tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;");
  } else {
    tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  }
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput(e) {
  this.style.height = "auto";
  this.style.height = (this.scrollHeight) + "px";
}
_x000D_
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>
_x000D_
_x000D_
_x000D_

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

MERGE INTO target
USING
(
    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    UNION ALL
    SELECT id, null some_value, 1 deleteMe
    FROM
    (
        SELECT id FROM target
        MINUS
        SELECT id FROM source
    )
) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
WHEN NOT MATCHED THEN
    INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;


--Results:
select * from target;

ID  SOME_VALUE   ISDELETED
1   new value 1  0
2   old value 2  1
3   new value 3  0

How do I apply CSS3 transition to all properties except background-position?

For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.

A simple demo below shows the difference. Check out full code

div:hover {
  width: 500px;
  height: 500px;
  border-radius: 0;
  transition: all 2s, border-radius 2s 4s;
}

Chrome will "combine" the two animation (which is like I expect), like below:

enter image description here

While Safari "separates" it (which may not be expected):

enter image description here

A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.

How to diff a commit with its parent?

git diff 15dc8 15dce~1

~1 means 'parent', ~2 'grandparent, etc.

Using Switch Statement to Handle Button Clicks

Hi its quite simple to make switch between buttons using switch case:-

 package com.example.browsebutton;


    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

        public class MainActivity extends Activity implements OnClickListener {
        Button b1,b2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                b1=(Button)findViewById(R.id.button1);

                b2=(Button)findViewById(R.id.button2);
                b1.setOnClickListener(this);
                b2.setOnClickListener(this);
            }



            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 int id=v.getId();
                 switch(id) {
                    case R.id.button1:
                  Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                //Your Operation

                  break;

                    case R.id.button2:
                          Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();


                          //Your Operation
                          break;
            }

        }}

Why can't I display a pound (£) symbol in HTML?

You could try using &pound; or &#163; instead of embedding the character directly; if you embed it directly, you're more likely to run into encoding issues in which your editor saves the file is ISO-8859-1 but it's interpreted as UTF-8, or vice versa.

If you want to embed it (or other Unicode characters) directly, make sure you actually save your file as UTF-8, and set the encoding as you did with the Content-Type header. Make sure when you get the file from the server that the header is present and correct, and that the file hasn't been transcoded by the web server.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I am using spring 3.0 and Hibernate 3.6 in my project. I ran into the same error just now. Googling this error message brought me to this page.

Funtik's comment on Jan 17 '12 at 8:49 helped me resolve the issue-

"This tells me that javassist cannot be accessed. How do you include this library into the project?"

So, I included java assist in my maven pom file as below:

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA</version>
</dependency>

This resolved the issue for me. Thanks Funtik.

http://localhost:50070 does not work HADOOP

if you are running and old version of Hadoop (hadoop 1.2) you got an error because http://localhost:50070/dfshealth.html does'nt exit. Check http://localhost:50070/dfshealth.jsp which works !

Is this very likely to create a memory leak in Tomcat?

The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.

Access XAMPP Localhost from Internet

First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here

For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.

If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.

Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).

For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.

Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).

As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns

I hope this helps.

How to use Git Revert

I reverted back a few commits by running 'git revert commit id' such as:

git revert b2cb7c248d416409f8eb42b561cbff91b0601712

Then i was prompted to commit the revert (just as you would when running 'git commit'). My default terminal program is Vim so i ran:

:wq 

Finally i pushed the change to the repository with:

git push

How to get image size (height & width) using JavaScript?

Before acquire element's attributes,the document page should be onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

Javascript to set hidden form value on drop down change

<form>
  <input type="hidden" name="selval">
  <select onchange="this.form.selval.value=this.selectedIndex">
    <option>val1</option>
    <option>val2</option>
  </select>
</form>

pure javascript from within a form

Error "The input device is not a TTY"

If you are (like me) using git bash on windows, you just need to put

winpty

before your 'docker line' :

winpty docker exec -it some_cassandra bash

Move div to new line

Try this

#movie_item {
    display: block;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
    background: red;
}

#movie_item_content {
    float: left;
    background: gold;
}

.movie_item_content_title {
    display: block;
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
    display: block;

}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

In Html

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
            <div class="movie_item_content_year">(1890-)</div>
        <div class="movie_item_content_title">title my film is a long word</div>
        <div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

I change position div year.

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

How do you connect to multiple MySQL databases on a single webpage?

If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.

You would connect through PDO, like this:

try {
  $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

(Of course replace databasename, username and password above)

You can then query the database like this:

$result = $db->query("select * from tablename");
foreach ($result as $row) {
  echo $row['foo'] . "\n";
}

Or, if you have variables:

$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();

If you need multiple connections open at once, you can simply create multiple instances of PDO:

try {
  $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
  $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

Disabling enter key for form

I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()

/*
 * Prevents default behavior of pushing enter button. This method doesn't work,
 * if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
 * the input. So method should be attached directly to the input 'onkeydown'
 */
function preventEnterKey(e) {
    // W3C (Chrome|FF) || IE
    e = e || window.event;
    var keycode = e.which || e.keyCode;
    if (keycode == 13) { // Key code of enter button
        // Cancel default action
        if (e.preventDefault) { // W3C
            e.preventDefault();
        } else { // IE
            e.returnValue = false;
        }
        // Cancel visible action
        if (e.stopPropagation) { // W3C
            e.stopPropagation();
        } else { // IE
            e.cancelBubble = true;
        }
        // We don't need anything else
        return false;
    }
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
    try {
        var els = document.getElementsByTagName('input');
        if (els) {
            for ( var i = 0; i < els.length; i++) {
                els[i].onkeydown = preventEnterKey;
            }
        }
    } catch (e) {
    }
}

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

Install specific branch from github using Npm

There are extra square brackets in the command you tried.

To install the latest version from the v1 branch, you can use:

npm install git://github.com/shakacode/bootstrap-loader.git#v1 --save

Windows batch: formatted date into variable

If you have Python installed, you can do

python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"

You can easily adapt the format string to your needs.

Prevent browser caching of AJAX call result

Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.

Of course this doesn't help if you have no control over the server.

How do I insert multiple checkbox values into a table?

You should specify

<input type="checkbox" name="Days[]" value="Daily">Daily<br>

as array.

Add [] to all names Days and work at php with this like an array.

After it, you can INSERT values at different columns at db, or use implode and save values into one column.


Didn't tested it, but you can try like this. Don't forget to replace mysql with mysqli.

<html>
<body>
<form method="post" action="chk123.php">
Flights on: <br/>
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
<input type="checkbox" name="Days[]" value="Monday">Monday<br>
<input type="checkbox" name="Days[]" value="Tuesday">Tuesday <br>
<input type="checkbox" name="Days[]" value="Wednesday">Wednesday<br>
<input type="checkbox" name="Days[]" value="Thursday">Thursday <br>
<input type="checkbox" name="Days[]" value="Friday">Friday<br>
<input type="checkbox" name="Days[]" value="Saturday">Saturday <br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

<?php

// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$checkBox = implode(',', $_POST['Days']);

if(isset($_POST['submit']))
{       
    $query="INSERT INTO example (orange) VALUES ('" . $checkBox . "')";     

    mysql_query($query) or die (mysql_error() );

    echo "Complete";

}

?>

Get safe area inset top and bottom heights

Swift 5 Extension

This can be used as a Extension and called with: UIApplication.topSafeAreaHeight

extension UIApplication {
    static var topSafeAreaHeight: CGFloat {
        var topSafeAreaHeight: CGFloat = 0
         if #available(iOS 11.0, *) {
               let window = UIApplication.shared.windows[0]
               let safeFrame = window.safeAreaLayoutGuide.layoutFrame
               topSafeAreaHeight = safeFrame.minY
             }
        return topSafeAreaHeight
    }
}

Extension of UIApplication is optional, can be an extension of UIView or whatever is preferred, or probably even better a global function.

Find Oracle JDBC driver in Maven repository

For dependency

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

Try

<repository>
    <id>mvnrepository</id>
    <url>http://nexus.saas.hand-china.com/content/repositories/rdc</url>
</repository>

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

Select SQL results grouped by weeks

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

How to override trait function and call it from the overridden function?

Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

trait A {
    protected function traitcalc($v) {
        return $v+1;
    }

    function calc($v) {
        return $this->traitcalc($v);
    }
}

class MyClass {
    use A;

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

class MyOtherClass {
    use A;
}


print (new MyClass())->calc(2); // will print 4

print (new MyOtherClass())->calc(2); // will print 3

How to concatenate string variables in Bash

foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World

In general to concatenate two variables you can just write them one after another:

a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World

How can I use jQuery in Greasemonkey?

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)

javac: invalid target release: 1.8

I got the same issue with netbeans, but mvn build is OK in cmd window. For me the issue resolved after changing netbeans' JDK (in netbeans.conf as below),

netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_91"


Edit: Seems it's mentioned here: netbeans bug 236364

Check whether user has a Chrome extension installed

I thought I would share my research on this. I needed to be able to detect if a specific extension was installed for some file:/// links to work. I came across this article here This explained a method of getting the manifest.json of an extension.

I adjusted the code a bit and came up with:

function Ext_Detect_NotInstalled(ExtName, ExtID) {
  console.log(ExtName + ' Not Installed');
  if (divAnnounce.innerHTML != '')
    divAnnounce.innerHTML = divAnnounce.innerHTML + "<BR>"

  divAnnounce.innerHTML = divAnnounce.innerHTML + 'Page needs ' + ExtName + ' Extension -- to intall the LocalLinks extension click <a href="https://chrome.google.com/webstore/detail/locallinks/' + ExtID + '">here</a>';
}

function Ext_Detect_Installed(ExtName, ExtID) {
  console.log(ExtName + ' Installed');
}

var Ext_Detect = function (ExtName, ExtID) {
  var s = document.createElement('script');
  s.onload = function () { Ext_Detect_Installed(ExtName, ExtID); };
  s.onerror = function () { Ext_Detect_NotInstalled(ExtName, ExtID); };
  s.src = 'chrome-extension://' + ExtID + '/manifest.json';
  document.body.appendChild(s);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

if (is_chrome == true) {
  window.onload = function () { Ext_Detect('LocalLinks', 'jllpkdkcdjndhggodimiphkghogcpida'); };
}

With this you should be able to use Ext_Detect(ExtensionName,ExtensionID) to detect the installation of any number of extensions.

Removing packages installed with go get

You can delete the archive files and executable binaries that go install (or go get) produces for a package with go clean -i importpath.... These normally reside under $GOPATH/pkg and $GOPATH/bin, respectively.

Be sure to include ... on the importpath, since it appears that, if a package includes an executable, go clean -i will only remove that and not archive files for subpackages, like gore/gocode in the example below.

Source code then needs to be removed manually from $GOPATH/src.

go clean has an -n flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean). It also has a tempting -r flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!

A complete example, which you could base a script on if you like:

$ go get -u github.com/motemen/gore

$ which gore
/Users/ches/src/go/bin/gore

$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a

$ go clean -i github.com/motemen/gore...

$ which gore

$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore

0 directories, 0 files

# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore

$ rm -rf $GOPATH/src/github.com/motemen/gore

Note that this information is based on the go tool in Go version 1.5.1.

How do I use raw_input in Python 3

How about the following one? Should allow you to use either raw_input or input in both Python2 and Python3 with the semantics of Python2's raw_input (aka the semantics of Python3's input)

# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x 
try: input = raw_input
except NameError: raw_input = input

JavaScript Array to Set

By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.

var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}


var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}

So, do not convert to set if you have repeated values in your array.

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

Create a custom callback in JavaScript

   function callback(e){
      return e;
   }
    var MyClass = {
       method: function(args, callback){
          console.log(args);
          if(typeof callback == "function")
          callback();
       }    
    }

==============================================

MyClass.method("hello",function(){
    console.log("world !");
});

==============================================

Result is:

hello world !

Most efficient way to reverse a numpy array

np.fliplr() flips the array left to right.

Note that for 1d arrays, you need to trick it a bit:

arr1d = np.array(some_sequence)
reversed_arr = np.fliplr([arr1d])[0]

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

How to unmount a busy device

Try the following, but before running it note that the -k flag will kill any running processes keeping the device busy.

The -i flag makes fuser ask before killing.

fuser -kim /address  # kill any processes accessing file
unmount /address

Is there a command to refresh environment variables from the command prompt in Windows?

I liked the approach followed by chocolatey, as posted in anonymous coward's answer, since it is a pure batch approach. However, it leaves a temporary file and some temporary variables lying around. I made a cleaner version for myself.

Make a file refreshEnv.bat somewhere on your PATH. Refresh your console environment by executing refreshEnv.

@ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!

REM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w

IF [%1]==[/?] GOTO :help
IF [%1]==[/help] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[] GOTO :main

ECHO Unknown command: %1
EXIT /b 1 

:help
ECHO Refresh the environment variables in the console.
ECHO.
ECHO   refreshEnv       Refresh all environment variables.
ECHO   refreshEnv /?        Display this help.
GOTO :EOF

:main
REM Because the environment variables may refer to other variables, we need a 2-step approach.
REM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and
REM may pose problems for files with an '!' in the name.
REM The option used here is to create a temporary batch file that will define all the variables.

REM Check to make sure we don't overwrite an actual file.
IF EXIST %TEMP%\__refreshEnvironment.bat (
  ECHO Environment refresh failed!
  ECHO.
  ECHO This script uses a temporary file "%TEMP%\__refreshEnvironment.bat", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.
  EXIT /b 1
)

REM Read the system environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"`) DO (
  REM /I -> ignore casing, since PATH may also be called Path
  IF /I NOT [%%I]==[PATH] (
    ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
  )
)

REM Read the user environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment`) DO (
  REM /I -> ignore casing, since PATH may also be called Path
  IF /I NOT [%%I]==[PATH] (
    ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
  )
)

REM PATH is a special variable: it is automatically merged based on the values in the
REM system and user variables.
REM Read the PATH variable from the system and user environment variables.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) DO (
  ECHO SET PATH=%%K>>%TEMP%\__refreshEnvironment.bat
)
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment /v PATH`) DO (
  ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\__refreshEnvironment.bat
)

REM Load the variable definitions from our temporary file.
CALL %TEMP%\__refreshEnvironment.bat

REM Clean up after ourselves.
DEL /Q %TEMP%\__refreshEnvironment.bat

ECHO Environment successfully refreshed.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Swift programmatically navigate to another view controller/scene

OperationQueue.main.addOperation {
   let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
   self.present(newViewController, animated: true, completion: nil)
}

It worked for me when I put the code inside of the OperationQueue.main.addOperation, that will execute in the main thread for me.

Cannot checkout, file is unmerged

To remove tracked files (first_file.txt) from git:

git rm first_file.txt

And to remove untracked files, use:

rm -r explore_california

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

How do I set a textbox's text to bold at run time?

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

Can there exist two main methods in a Java program?

Here you can see that there are 2 public static void main (String args[]) in a single file with the name Test.java (specifically didn't use the name of file as either of the 2 classes names) and the 2 classes are with the default access specifier.

class Sum {

    int add(int a, int b) {
        return (a+b);   
    }

    public static void main (String args[]) {
        System.out.println(" using Sum class");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(5, 10));
    }

    public static void main (int i) {
        System.out.println(" Using Sum class main function with integer argument");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(20, 10));
    }
}

class DefClass {

    public static void main (String args[]) {
        System.out.println(" using DefClass");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(5, 10));
        Sum.main(null);
        Sum.main(1);
    }
}

When we compile the code Test.java it will generate 2 .class files (viz Sum.class and DefClass.class) and if we run Test.java we cannot run it as it won't find any main class with the name Test. Instead if we do java Sum or java DefClass both will give different outputs using different main(). To use the main method of Sum class we can use the class name Sum.main(null) or Sum.main(1)//Passing integer value in the DefClass main().

In a class scope we can have only one public static void main (String args[]) per class since a static method of a class belongs to a class and not to its objects and is called using its class name. Even if we create multiple objects and call the same static methods using them then the instance of the static method to which these call will refer will be the same.

We can also do the overloading of the main method by passing different set of arguments in the main. The Similar example is provided in the above code but by default the control flow will start with the public static void main (String args[]) of the class file which we have invoked using java classname. To invoke the main method with other set of arguments we have to explicitly call it from other classes.

Proper use of 'yield return'

This is kinda besides the point, but since the question is tagged best-practices I'll go ahead and throw in my two cents. For this type of thing I greatly prefer to make it into a property:

public static IEnumerable<Product> AllProducts
{
    get {
        using (AdventureWorksEntities db = new AdventureWorksEntities()) {
            var products = from product in db.Product
                           select product;

            return products;
        }
    }
}

Sure, it's a little more boiler-plate, but the code that uses this will look much cleaner:

prices = Whatever.AllProducts.Select (product => product.price);

vs

prices = Whatever.GetAllProducts().Select (product => product.price);

Note: I wouldn't do this for any methods that may take a while to do their work.

How to add to the end of lines containing a pattern with sed or awk?

Here is another simple solution using sed.

$ sed -i 's/all.*/& anotherthing/g' filename.txt

Explanation:

all.* means all lines started with 'all'.

& represent the match (ie the complete line that starts with 'all')

then sed replace the former with the later and appends the ' anotherthing' word

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Using Custom Domains With IIS Express

This method has been tested and worked with ASP.NET Core 3.1 and Visual Studio 2019.

.vs\PROJECTNAME\config\applicationhost.config

Change "*:44320:localhost" to "*:44320:*".

<bindings>
    <binding protocol="http" bindingInformation="*:5737:localhost" />
    <binding protocol="https" bindingInformation="*:44320:*" />
</bindings>

Both links work:

Now if you want the app to work with the custom domain, just add the following line to the host file:

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 customdomain

Now:

  • https://customdomain:44320

NOTE: If your app works without SSL, change the protocol="http" part.

Check whether number is even or odd

If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.

Android Split string

     String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
     StringTokenizer st = new StringTokenizer(s, "|");
        String community = st.nextToken();
        String helpDesk = st.nextToken(); 
        String localEmbassy = st.nextToken();
        String referenceDesk = st.nextToken();
        String siteNews = st.nextToken();

Find the max of 3 numbers in Java with different data types

Java 8 way. Works for multiple parameters:

Stream.of(first, second, third).max(Integer::compareTo).get()

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

What is 'Currying'?

An example of currying would be when having functions you only know one of the parameters at the moment:

For example:

func aFunction(str: String) {
    let callback = callback(str) // signature now is `NSData -> ()`
    performAsyncRequest(callback)
}

func callback(str: String, data: NSData) {
    // Callback code
}

func performAsyncRequest(callback: NSData -> ()) {
    // Async code that will call callback with NSData as parameter
}

Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

You can use this code to get current URL:

echo url()->current();

echo url()->full();

I get this from Laravel documents.

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

Size-limited queue that holds last N elements in Java

    public class ArrayLimitedQueue<E> extends ArrayDeque<E> {

    private int limit;

    public ArrayLimitedQueue(int limit) {
        super(limit + 1);
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        boolean added = super.add(o);
        while (added && size() > limit) {
            super.remove();
        }
        return added;
    }

    @Override
    public void addLast(E e) {
        super.addLast(e);
        while (size() > limit) {
            super.removeLast();
        }
    }

    @Override
    public boolean offerLast(E e) {
        boolean added = super.offerLast(e);
        while (added && size() > limit) {
            super.pollLast();
        }
        return added;
    }
}

What to do about Eclipse's "No repository found containing: ..." error messages?

In my case I was getting the above mentioned errors only for a particular update site and eclipse-java-mars-R. Other update sites were allowing me to update, and, using other versions of Eclipse I was able to install from the update site which was causing problems for my Java Mars R Eclipse.

Deleting the cache folder in /Users/myname/.eclipse/org.eclipse.oomph.p2 solved the problem (my coworker, not me, came up with this solution)

Why is a "GRANT USAGE" created the first time I grant a user privileges?

I was trying to find the meaning of GRANT USAGE on *.* TO and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password will be granted when you create the user with the following command (CREATE):

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; 

When you grant privilege with GRANT, new privilege s will be added on top of it.

How to flatten only some dimensions of a numpy array

A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":

e.g. to flatten all but the last dimension:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)

Explain the "setUp" and "tearDown" Python methods used in test cases

In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.

You can read more with examples here.

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.

For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.

Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.

So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.

You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.

If you are looking for an easy example please use the following link with example

How to pass arguments within docker-compose?

Now docker-compose supports variable substitution.

Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration in your docker-compose.yml file:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

calling javascript function on OnClientClick event of a Submit button

The above solutions must work. However you can try this one:

OnClientClick="return SomeMethod();return false;"

and remove return statement from the method.

How to get the current directory in a C program?

Look up the man page for getcwd.

Angular directives - when and how to use compile, controller, pre-link and post-link

Controller function

Each directive's controller function is called whenever a new related element is instantiated.

Officially, the controller function is where one:

  • Defines controller logic (methods) that may be shared between controllers.
  • Initiates scope variables.

Again, it is important to remember that if the directive involves an isolated scope, any properties within it that inherit from the parent scope are not yet available.

Do:

  • Define controller logic
  • Initiate scope variables

Do not:

  • Inspect child elements (they may not be rendered yet, bound to scope, etc.).

Hide all elements with class using plain Javascript

In the absence of jQuery, I would use something like this:

<script>
    var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
    for(var i = 0; i < divsToHide.length; i++){
        divsToHide[i].style.visibility = "hidden"; // or
        divsToHide[i].style.display = "none"; // depending on what you're doing
    }
<script>

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

How to add hamburger menu in bootstrap

To create icon you can use Glyphicon in Bootstrap:

<a href="#" class="btn btn-info btn-sm">
    <span class="glyphicon glyphicon-menu-hamburger"></span>
</a>

And then control size of icon in css:

.glyphicon-menu-hamburger {
  font-size: npx;
}

How to size an Android view based on its parent's dimensions

I've been struggling this question for a long time, I want to change my DrawerLayout's drawer width, which is the second child of its parent. Recently I figured it out, but doesn't know if there's a better idea.

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    super.onLayout(changed, l, t, r, b)
    (getChildAt(1).layoutParams as LayoutParams).width = measuredWidth/2
}

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

Is there a better way to compare dictionary values

If your values are hashable (ie. strings), then you can simply compare the ItemsView of the two dicts.

https://docs.python.org/3/library/stdtypes.html#dict-views

set_with_unique_key_value_pairs = dict1.items() ^ dict2.items()
set_with_matching_key_value_pairs = dict1.items() & dict2.items()

Any set operations are available to you.

Since you might not care about keys in this case, you can also just use the ValuesView (again, provided the values are hashable).

set_with_matching_values = dict1.values() & dict2.values()

How to replace multiple substrings of a string?

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can apply the replacements within a list comprehension:

# text = "The quick brown fox jumps over the lazy dog"
# replacements = [("brown", "red"), ("lazy", "quick")]
[text := text.replace(a, b) for a, b in replacements]
# text = 'The quick red fox jumps over the quick dog'

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

Virtual Memory Usage from Java under Linux, too much memory used

Sun's java 1.4 has the following arguments to control memory size:

-Xmsn Specify the initial size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 1MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 2MB. Examples:

           -Xms6291456
           -Xms6144k
           -Xms6m

-Xmxn Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html

Java 5 and 6 have some more. See http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp

How do I create a ListView with rounded corners in Android?

to make border u have to make another xml file with property of solid and corners in the drawable folder and calls it in background

How to call VS Code Editor from terminal / command line

When installing on Windows, you will be prompted to add VS Code to your PATH.

I was trying to figure out how to open files with VS Code from the command line and I already had the capability - I just forgot I had already added it. You might already have it installed - check by navigating to a folder you want to open and running the command code . to open that folder.

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

Skip to next iteration in loop vba

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

Import Libraries in Eclipse?

If you want to get this library into your library and use it, follow these steps:

  1. You can create a new folder within Eclipse by right-clicking on your project, and selecting New Folder. The library folder is traditionally called lib.

  2. Drag and drop your jar folder into the new lib folder, and when prompted select Copy Files.

  3. Selecting the Project tab at the top of the screen, and click Properties.

  4. Select Java Build Path followed by the Libraries tab.

  5. Click the Add JARs… button and select your JAR file from within the lib folder.

  6. Your JAR file will now appear in both the lib and Referenced Libraries folders. You can explore the JAR's resources by clicking Referenced Libraries.

How to add property to a class dynamically?

I asked a similary question on this Stack Overflow post to create a class factory which created simple types. The outcome was this answer which had a working version of the class factory. Here is a snippet of the answer:

def Struct(*args, **kwargs):
    def init(self, *iargs, **ikwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "MyStruct")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()})

>>> Person = Struct('fname', 'age')
>>> person1 = Person('Kevin', 25)
>>> person2 = Person(age=42, fname='Terry')
>>> person1.age += 10
>>> person2.age -= 10
>>> person1.fname, person1.age, person2.fname, person2.age
('Kevin', 35, 'Terry', 32)
>>>

You could use some variation of this to create default values which is your goal (there is also an answer in that question which deals with this).

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

What Does 'zoom' do in CSS?

zoom is a css3 spec for the @viewport descriptor, as described here

http://dev.w3.org/csswg/css-device-adapt/#zoom-desc

used to zoom the entire viewport ('screen'). it also happens to zoom individuals elements in a lot of browsers, but not all. css3 specifies transform:scale should be used to achieve such an effect:

http://www.w3.org/TR/css3-transforms/#transform-functions

but it works a little different than the 'element zoom' in those browsers that support it.

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

Embed image in a <button> element

Try like this format and use "width" attribute to manage the image size, it is simple. JavaScript can be implemented in element too.

_x000D_
_x000D_
<button><img src=""></button>
_x000D_
_x000D_
_x000D_

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

It's a pretty common problem in Windows. You need just to set cacert.pem to curl.cainfo.

Since PHP 5.3.7 you could do:

  1. download https://curl.haxx.se/ca/cacert.pem and save it somewhere.
  2. update php.ini -- add curl.cainfo = "PATH_TO/cacert.pem"

Otherwise you will need to do the following for every cURL resource:

curl_setopt ($ch, CURLOPT_CAINFO, "PATH_TO/cacert.pem");

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

Java equivalent to #region in C#

Actually johann, the # indicates that it's a preprocessor directive, which basically means it tells the IDE what to do.

In the case of using #region and #endregion in your code, it makes NO difference in the final code whether it's there or not. Can you really call it a language element if using it changes nothing?

Apart from that, java doesn't have preprocessor directives, which means the option of code folding is defined on a per-ide basis, in netbeans for example with a //< code-fold> statement

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you have msi installer open it with Orca (tool from Microsoft), table Property (rows UpgradeCode, ProductCode, Product version etc) or table Upgrade column Upgrade Code.

Try to find instller via registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall find required subkey and watch value InstallSource. Maybe along the way you'll be able to find the MSI file.

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

fatal: could not create work tree dir 'kivy'

You should do the command in a directory where you have write permission. So:

cd ~/
mkdir code
cd code
git clone https://github.com/kivy/kivy

For example.

Refused to apply inline style because it violates the following Content Security Policy directive

Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.

Remove Trailing Spaces and Update in Columns in SQL Server

If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.

SELECT TRIM(ColumnName) from TableName;

For other SQL SERVER Database you can use the below query.

SELECT LTRIM(RTRIM(ColumnName)) from TableName

LTRIM - Removes spaces from the left

example: select LTRIM(' test ') as trim = 'test '

RTRIM - Removes spaces from the right

example: select RTRIM(' test ') as trim = ' test'

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

For me Visual Studio had created a projectname.v11 of type "Visual Studio Solution User Options". I deleted this file and restarted and everything was fine.

Hello World in Python

Unfortunately the xkcd comic isn't completely up to date anymore.

https://imgs.xkcd.com/comics/python.png

Since Python 3.0 you have to write:

print("Hello world!")

And someone still has to write that antigravity library :(

remove item from array using its name / value

You can do it with _.pullAllBy.

_x000D_
_x000D_
var countries = {};_x000D_
_x000D_
countries.results = [_x000D_
    {id:'AF',name:'Afghanistan'},_x000D_
    {id:'AL',name:'Albania'},_x000D_
    {id:'DZ',name:'Algeria'}_x000D_
];_x000D_
_x000D_
// Remove element by id_x000D_
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');_x000D_
_x000D_
// Remove element by name_x000D_
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');_x000D_
console.log(countries);
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
  top: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Call a function on click event in Angular 2

Component code:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]
  }

  public open(event, item) {
    alert('Open ' + item);
  }

}

View:

<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of items" (click)="open($event, item)">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }

Angular2 equivalent of $document.ready()

You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

This is Dart code (I don't know TypeScript) but should't be to hard to translate

@Component(selector: 'app-element')
@View(
    templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
  ElementRef elementRef;
  AppElement(this.elementRef);

  void ngOnInit() {
    DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
  }
}

Can I give the col-md-1.5 in bootstrap?

This question is quite old, but I have made it that way (in TYPO3).

Firstly, I have made a own accessible css-class which I can choose on every content element manually.

Then, I have made a outer three column element with 11 columns (1 - 9 - 1), finally, I have modified the column width of the first and third column with CSS to 12.499999995%.

How to put php inside JavaScript?

Try this:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

Pythonic way to check if a list is sorted or not

I use this one-liner based on numpy.diff():

def issorted(x):
    """Check if x is sorted"""
    return (numpy.diff(x) >= 0).all() # is diff between all consecutive entries >= 0?

I haven't really timed it against any other method, but I assume it's faster than any pure Python method, especially for large n, since the loop in numpy.diff (probably) runs directly in C (n-1 subtractions followed by n-1 comparisons).

However, you need to be careful if x is an unsigned int, which might cause silent integer underflow in numpy.diff(), resulting in a false positive. Here's a modified version:

def issorted(x):
    """Check if x is sorted"""
    try:
        if x.dtype.kind == 'u':
            # x is unsigned int array, risk of int underflow in np.diff
            x = numpy.int64(x)
    except AttributeError:
        pass # no dtype, not an array
    return (numpy.diff(x) >= 0).all()

installing python packages without internet and using source code as .tar.gz and .whl

This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.

So, I downloaded and installed dependencies first and then installed with below command. It worked

python -m pip install filename.tar.gz

How to parse JSON in Kotlin?

You can use this library https://github.com/cbeust/klaxon

Klaxon is a lightweight library to parse JSON in Kotlin.

How to find event listeners on a DOM node when debugging or from the JavaScript code?

If you just need to inspect what's happening on a page, you might try the Visual Event bookmarklet.

Update: Visual Event 2 available.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

LINQ: Select an object and change some properties without creating a new object

We often run into this where we want to include a the index value and first and last indicators in a list without creating a new object. This allows you to know the position of the item in your list, enumeration, etc. without having to modify the existing class and then knowing whether you're at the first item in the list or the last.

foreach (Item item in this.Items
    .Select((x, i) => {
    x.ListIndex = i;
    x.IsFirst = i == 0;
    x.IsLast = i == this.Items.Count-1;
    return x;
}))

You can simply extend any class by using:

public abstract class IteratorExtender {
    public int ListIndex { get; set; }
    public bool IsFirst { get; set; } 
    public bool IsLast { get; set; } 
}

public class Item : IteratorExtender {}

How can I make a button have a rounded border in Swift?

To do this job in storyboard (Interface Builder Inspector)

With help of IBDesignable, we can add more options to Interface Builder Inspector for UIButton and tweak them on storyboard. First, add the following code to your project.

@IBDesignable extension UIButton {

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}

Then simply set the attributes for buttons on storyboard.

enter image description here

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

You have to add empty option to solve it,

I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.

<select onChange="jsFunction()" id="selectOpt">
    <option value="1" onclick="jsFunction()">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

function jsFunction(){
  var myselect = document.getElementById("selectOpt");
  alert(myselect.options[myselect.selectedIndex].value);
}

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

For me the problem was the execution of clone via sudo.

If you clone to a directory where you have user permission ( /home/user/git) it will work fine.

(Explanation: Running a command as superuser will not work with the same public key as running a command as user. Therefore Github refused the connection.)

This solution requires a SSH key already to be set up: https://help.github.com/articles/generating-ssh-keys

How to resolve the error on 'react-native start'

You can go to...

\node_modules\metro-config\src\defaults\blacklist.js and change...

var sharedBlacklist = [   /node_modules[/\\]react[/\\]dist[/\\].*/,  
/website\/node_modules\/.*/,   /heapCapture\/bundle\.js/,  
/.*\/__tests__\/.*/ ];

for this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

Tomcat request timeout

If you are trying to prevent a request from running too long, then setting a timeout in Tomcat will not help you. As Chris says, you can set the global timeout value for Tomcat. But, from The Apache Tomcat Connector - Generic HowTo Timeouts, see the Reply Timeout section:

JK can also use a timeout on request replies. This timeout does not measure the full processing time of the response. Instead it controls, how much time between consecutive response packets is allowed.

In most cases, this is what one actually wants. Consider for example long running downloads. You would not be able to set an effective global reply timeout, because downloads could last for many minutes. Most applications though have limited processing time before starting to return the response. For those applications you could set an explicit reply timeout. Applications that do not harmonise with reply timeouts are batch type applications, data warehouse and reporting applications which are expected to observe long processing times.

If JK aborts waiting for a response, because a reply timeout fired, there is no way to stop processing on the backend. Although you free processing resources in your web server, the request will continue to run on the backend - without any way to send back a result once the reply timeout fired.

So Tomcat will detect that the servlet has not responded within the timeout and will send back a response to the user, but will not stop the thread running. I don't think you can achieve what you want to do.

How to insert a blob into a database using sql server management studio

Do you need to do it from mgmt studio? Here's how we do it from cmd line:

"C:\Program Files\Microsoft SQL Server\MSSQL\Binn\TEXTCOPY.exe" /S < Server> /D < DataBase> /T mytable /C mypictureblob /F "C:\picture.png" /W"where RecId=" /I

PHP mySQL - Insert new record into table with auto-increment on primary key

I prefer this syntaxis:

$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";

jQuery bind to Paste Event, how to get the content of the paste

It would appear as though this event has some clipboardData property attached to it (it may be nested within the originalEvent property). The clipboardData contains an array of items and each one of those items has a getAsString() function that you can call. This returns the string representation of what is in the item.

Those items also have a getAsFile() function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry() function).

For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:

$(element).bind("paste", function (e) {
    e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
        debugger; 
        // pStringRepresentation now contains the string representation of what was pasted.
        // This does not include HTML or any markup. Essentially jQuery's $(element).text()
        // function result.
    });
});

You'll want to perform an iteration through the items, keeping a string concatenation result.

The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

"Full screen" <iframe>

Impossible to say without seeing a live example, but try giving both bodies margin: 0px

ImportError: No module named scipy

Try to install it as a python package using pip as follows

$ sudo apt-get install python-scipy

If you want to run a python 3.x script, install scipy by:

$ pip3 install scipy
Otherwise install it by:
$ pip install scipy

Can you issue pull requests from the command line on GitHub?

I ended up making my own, I find that it works better the other solutions that were around.

https://npmjs.org/package/pullr

How do you handle multiple submit buttons in ASP.NET MVC Framework?

There are three ways by which you can solve the above issue

  1. HTML way
  2. Jquery way
  3. “ActionNameSelectorAttribute” way

Below is a video which summarizes all the three approaches in a demonstrative way.

https://www.facebook.com/shivprasad.koirala/videos/vb.100002224977742/809335512483940

HTML way :-

In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

<form action="Action1" method=post>
<input type=”submit” name=”Submit1”/>
</form>

<form action="Action2" method=post>
<input type=”submit” name=”Submit2”>
</form>

Ajax way :-

In case you are a Ajax lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1” , see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions are binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.

<Script language="javascript">
function Fun1()
{
$.post(“/Action1”,null,CallBack1);
}
function Fun2()
{
$.post(“/Action2”,null,CallBack2);
}
</Script>

<form action="/Action1" method=post>
<input type=submit name=sub1 onclick=”Fun2()”/>
</form>
<form action="/Action2" method=post>
<input type=submit name=sub2 onclick=”Fun1()”/>
</form>

Using “ActionNameSelectorAttribute”:-

This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.

So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server.

You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.

<form action=”Customer” method=post>
<input type=submit value="Save" name="Save" /> <br />
<input type=submit value="Delete" name="Delete"/>
</form>

So when the submit button is clicked , it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.

enter image description here

So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.

We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

public class SubmitButtonSelector : ActionNameSelectorAttribute
    {
        public string Name { get; set; }
        public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
        {
            // Try to find out if the name exists in the data sent from form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
            if (value != null)
            {
                return true;
            }
            return false;

        }
    }

The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
      {
        return true;
      }
      return false;

This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.

public class CustomerController : Controller
{
        [SubmitButtonSelector(Name="Save")]
        public ActionResult Save()
        {
            return Content("Save Called");
        }
        [SubmitButtonSelector(Name = "Delete")]
        public ActionResult Delete()
        {
            return Content("Delete Called");
        }
}

Javascript : Send JSON Object with Ajax?

With jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

Without jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));

"Parameter not valid" exception loading System.Drawing.Image

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?

Android studio- "SDK tools directory is missing"

This was an issue for me because I already had the SDK installed under a different directory. In order to tell Android Studio to where the SDK is you need to get to the settings, but the "SDK tools directory is missing" dialog always exits the whole program when you click "Finish". Here's how I "solved" it:

  1. Delete your ~/.Android* folders (losing all of your settings :/).
  2. Run Android Studio. It will show you a welcome wizard where it tries to download the SDK again (and fails due to my rubbish internet).
  3. Click the X on the wizard window. That will enable you to get to the normal welcome dialog.
  4. Go to Settings->Project Defaults->Project Structure and change the Android SDK location to the correct one.

Deleting the .Android Studio folders may be unnecessary - I never tried pressing the X on the original error dialog - I only tried "Finish" which exits Android Studio. It is possible if you click the X you can get to settings but unfortunately I can't go back and check now.

How can I convert a Unix timestamp to DateTime and vice versa?

I needed to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision and haven't found an answer here so I thought I just might add mine:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
    return _epochTime.AddTicks(
        unixTime.Seconds * TimeSpan.TicksPerSecond +
        unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}

What is a Subclass

Subclass is to Class as Java is to Programming Language.

Find non-ASCII characters in varchar columns using SQL Server

Here is a UDF I built to detectc columns with extended ascii charaters. It is quick and you can extended the character set you want to check. The second parameter allows you to switch between checking anything outside the standard character set or allowing an extended set:

create function [dbo].[udf_ContainsNonASCIIChars]
(
@string nvarchar(4000),
@checkExtendedCharset bit
)
returns bit
as
begin

    declare @pos int = 0;
    declare @char varchar(1);
    declare @return bit = 0;

    while @pos < len(@string)
    begin
        select @char = substring(@string, @pos, 1)
        if ascii(@char) < 32 or ascii(@char) > 126 
            begin
                if @checkExtendedCharset = 1
                    begin
                        if ascii(@char) not in (9,124,130,138,142,146,150,154,158,160,170,176,180,181,183,184,185,186,192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,209,210,211,212,213,214,216,217,218,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255)
                            begin
                                select @return = 1;
                                select @pos = (len(@string) + 1)
                            end
                        else
                            begin
                                select @pos = @pos + 1
                            end
                    end
                else
                    begin
                        select @return = 1;
                        select @pos = (len(@string) + 1)    
                    end
            end
        else
            begin
                select @pos = @pos + 1
            end
    end

    return @return;

end

USAGE:

select Address1 
from PropertyFile_English
where udf_ContainsNonASCIIChars(Address1, 1) = 1

Getting full JS autocompletion under Sublime Text

As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Inspired by Johann's table, I've decided to extend the table. I wanted to see which ASCII characters get encoded.

screenshot of console.table

_x000D_
_x000D_
var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";_x000D_
_x000D_
var encoded = [];_x000D_
_x000D_
ascii.split("").forEach(function (char) {_x000D_
    var obj = { char };_x000D_
    if (char != encodeURI(char))_x000D_
        obj.encodeURI = encodeURI(char);_x000D_
    if (char != encodeURIComponent(char))_x000D_
        obj.encodeURIComponent = encodeURIComponent(char);_x000D_
    if (obj.encodeURI || obj.encodeURIComponent)_x000D_
        encoded.push(obj);_x000D_
});_x000D_
_x000D_
console.table(encoded);
_x000D_
_x000D_
_x000D_

Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.


Just to be extra, I'm adding another table for urlencode() vs rawurlencode(). The only difference seems to be the encoding of space character.

screenshot of console.table

<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
    $obj = ["char" => $char];
    if ($char != urlencode($char))
        $obj["urlencode"] = urlencode($char);
    if ($char != rawurlencode($char))
        $obj["rawurlencode"] = rawurlencode($char);
    if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
        $encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>

SSRS chart does not show all labels on Horizontal axis

(Three years late...) but I believe the answer to your second question is that SSRS essentially treats data from your datasets as unsorted; I'm not sure if it ignores any ORDER BY in the sql, or if it just assumes the data is unsorted.

To sort your groups in a particular order, you need to specify it in the report:

  • Select the chart,
  • In the Chart Data popup window (where you specify the Category Groups), right-click your Group and click Category Group Properties,
  • Click on the Sorting option to see a control to set the Sort order

For the report I just created, the default sort order on the category was alphabetic on the category group which was basically a string code. But sometimes it can be useful to sort by some other characteristic of the data; for example, my report is of Average and Maximum processing times for messages identified by some code (the category). By setting the sort order of the group to be on [MaxElapsedMs], Z->A it draws my attention to the worst-performing message-types.

A stacked bar chart with categories sorted by the value in one of the fields

This sort of presentation won't be useful for every report but it can be an excellent tool to guide readers to have a better understanding of the data; though on other occasions you might prefer a report to have the same ordering every time it runs, in which case sorting on the category label itself may be best... and I guess there are circumstances where changing the sort order could harm understanding, such as if the categories implied some sort of ordering (such as date values?)

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

How can I send an HTTP POST request to a server from Excel using VBA?

If you need it to work on both Mac and Windows, you can use QueryTables:

With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
    .PostText = "origin_airport=MSN&destination_airport=ORD"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    .Refresh
End With

Notes:

  • Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
  • Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
  • This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.

For more details, you can see my full summary about "using web services from Excel."

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

How to convert Java String to JSON Object

Your json -

{
    "title":"Free Music Archive - Genres",
    "message":"",
    "errors":[
    ],
    "total":"163",
    "total_pages":82,
    "page":1,
    "limit":"2",
    "dataset":[
    {
    "genre_id":"1",
    "genre_parent_id":"38",
    "genre_title":"Avant-Garde",
    "genre_handle":"Avant-Garde",
    "genre_color":"#006666"
    },
    {
    "genre_id":"2",
    "genre_parent_id":null,
    "genre_title":"International",
    "genre_handle":"International",
    "genre_color":"#CC3300"
    }
    ]
    }

Using the JSON library from json.org -

JSONObject o = new JSONObject(jsonString);

NOTE:

The following information will be helpful to you - json.org.

UPDATE:

import org.json.JSONObject;
 //Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
 api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
 //Return the JSON Response from the API
 BufferedReader br = new BufferedReader(new         
 InputStreamReader(seatURL.openStream(),
 Charset.forName("UTF-8")));
 String readAPIResponse = " ";
 StringBuilder jsonString = new StringBuilder();
 while((readAPIResponse = br.readLine()) != null){
   jsonString.append(readAPIResponse);
 }
 JSONObject jsonObj = new JSONObject(jsonString.toString());
 System.out.println(jsonString);
 System.out.println("---------------------------");
 System.out.println(jsonObj);

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

What's the difference between map() and flatMap() methods in Java 8?

Stream operations flatMap and map accept a function as input.

flatMap expects the function to return a new stream for each element of the stream and returns a stream which combines all the elements of the streams returned by the function for each element. In other words, with flatMap, for each element from the source, multiple elements will be created by the function. http://www.zoftino.com/java-stream-examples#flatmap-operation

map expects the function to return a transformed value and returns a new stream containing the transformed elements. In other words, with map, for each element from the source, one transformed element will be created by the function. http://www.zoftino.com/java-stream-examples#map-operation

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

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

import java.util.Random;

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

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

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

create a text file using javascript

From a web page this cannot work since IE restricts the use of that object.

Getting values from JSON using Python

There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:

j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon

Generate PDF from Swagger API documentation

I created a web site https://www.swdoc.org/ that specifically addresses the problem. So it automates swagger.json -> Asciidoc, Asciidoc -> pdf transformation as suggested in the answers. Benefit of this is that you dont need to go through the installation procedures. It accepts a spec document in form of url or just a raw json. Project is written in C# and its page is https://github.com/Irdis/SwDoc

EDIT

It might be a good idea to validate your json specs here: http://editor.swagger.io/ if you are having any problems with SwDoc, like the pdf being generated incomplete.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

First download this JavaScript code, JSON2.js, that will help us serialize the object into a string.

In my example I'm posting the rows of a jqGrid via Ajax:

    var commissions = new Array();
    // Do several row data and do some push. In this example is just one push.
    var rowData = $(GRID_AGENTS).getRowData(ids[i]);
    commissions.push(rowData);
    $.ajax({
        type: "POST",
        traditional: true,
        url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions',
        async: true,
        data: JSON.stringify(commissions),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.Result) {
                jQuery(GRID_AGENTS).trigger('reloadGrid');
            }
            else {
                jAlert("A problem ocurred during updating", "Commissions Report");
            }
        }
    });

Now on the controller:

    [HttpPost]
    [JsonFilter(Param = "commissions", JsonDataType = typeof(List<CommissionsJs>))]
    public ActionResult SubmitCommissions(List<CommissionsJs> commissions)
    {
        var result = dosomething(commissions);
        var jsonData = new
        {
            Result = true,
            Message = "Success"
        };
        if (result < 1)
        {
            jsonData = new
            {
                Result = false,
                Message = "Problem"
            };
        }
        return Json(jsonData);
    }

Create a JsonFilter Class (thanks to JSC reference).

    public class JsonFilter : ActionFilterAttribute
    {
        public string Param { get; set; }
        public Type JsonDataType { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
            {
                string inputContent;
                using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
                {
                    inputContent = sr.ReadToEnd();
                }
                var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
                filterContext.ActionParameters[Param] = result;
            }
        }
    }

Create another class so the filter can parse the JSON string to the actual manipulable object: This class comissionsJS are all the rows of my jqGrid.

    public class CommissionsJs
    {
        public string Amount { get; set; }

        public string CheckNumber { get; set; }

        public string Contract { get; set; }
        public string DatePayed { get; set; }
        public string DealerName { get; set; }
        public string ID { get; set; }
        public string IdAgentPayment { get; set; }
        public string Notes { get; set; }
        public string PaymentMethodName { get; set; }
        public string RowNumber { get; set; }
        public string AgentId { get; set; }
    }

I hope this example helps to illustrate how to post a complex object.

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

gsub("\\..*","",a)
[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

How do I find duplicate values in a table in Oracle?

Also u can try something like this to list all duplicate values in a table say reqitem

SELECT count(poid) 
FROM poitem 
WHERE poid = 50 
AND rownum < any (SELECT count(*)  FROM poitem WHERE poid = 50) 
GROUP BY poid 
MINUS
SELECT count(poid) 
FROM poitem 
WHERE poid in (50)
GROUP BY poid 
HAVING count(poid) > 1;

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

How to use C++ in Go

You can't quite yet from what I read in the FAQ:

Do Go programs link with C/C++ programs?

There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs.

The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

View stored procedure/function definition in MySQL

An alternative quick and hacky solution if you want to get an overview of all the produres there are, or run into the issue of only getting the procedure header shown by SHOW CREATE PROCEDURE:

mysqldump --user=<user> -p --no-data --routines <database>

It will export the table descriptions as well, but no data. Works well for sniffing around unknown or forgotten schemas... ;)

How can I pause setInterval() functions?

You could use a flag to keep track of the status:

_x000D_
_x000D_
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = 0;_x000D_
var t = window.setInterval(function() {_x000D_
  if(!isPaused) {_x000D_
    time++;_x000D_
    output.text("Seconds: " + time);_x000D_
  }_x000D_
}, 1000);_x000D_
_x000D_
//with jquery_x000D_
$('.pause').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = true;_x000D_
});_x000D_
_x000D_
$('.play').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = false;_x000D_
});
_x000D_
h1 {_x000D_
    font-family: Helvetica, Verdana, sans-serif;_x000D_
    font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="play">Play</button>_x000D_
<button class="pause">Pause</button>
_x000D_
_x000D_
_x000D_

This is just what I would do, I'm not sure if you can actually pause the setInterval.

Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.

convert a JavaScript string variable to decimal/money

Yes -- parseFloat.

parseFloat(document.getElementById(amtid4).innerHTML);

For formatting numbers, use toFixed:

var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);

num is now a string with the number formatted with two decimal places.

How to break long string to multiple lines

you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing

SqlQueryString = "Insert into Employee values(" 
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"

Get bitcoin historical data

In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.

The script uses python websocket-client and pusher_client_python libraries, so install them.

#!/usr/bin/python

import pusherclient
import time
import logging
import sys
import datetime
import signal
import os

logging.basicConfig()
log_file_fd = None

def sigint_and_sigterm_handler(signal, frame):
    global log_file_fd
    log_file_fd.close()
    sys.exit(0)


class BitstampLogger:

    def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
        self.channel = channel
        self.event = event
        self.log_file_fd = open(log_file_path, "a")
        self.log_file_reload_path = log_file_reload_path
        self.pusher = pusherclient.Pusher(pusher_key)
        self.pusher.connection.logger.setLevel(logging.WARNING)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()

    def callback(self, data):
        utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
        line = str(utc_timestamp) + " " + data + "\n"
        if os.path.exists(self.log_file_reload_path):
            os.remove(self.log_file_reload_path)
            self.log_file_fd.close()
            self.log_file_fd = open(log_file_path, "a")
        self.log_file_fd.write(line)

    def connect_handler(self, data):
        channel = self.pusher.subscribe(self.channel)
        channel.bind(self.event, self.callback)


def main(log_file_path, log_file_reload_path):
    global log_file_fd
    bitstamp_logger = BitstampLogger(
        log_file_path,
        log_file_reload_path,
        "de504dc5763aeef9ff52",
        "live_trades",
        "trade")
    log_file_fd = bitstamp_logger.log_file_fd
    signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
    signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
    while True:
        time.sleep(1)


if __name__ == '__main__':
    log_file_path = sys.argv[1]
    log_file_reload_path = sys.argv[2]
    main(log_file_path, log_file_reload_path

and logrotate file config

/mnt/data/bitstamp_logs/bitstamp-trade.log
{
    rotate 10000000000
    minsize 10M
    copytruncate
    missingok
    compress
    postrotate
        touch /mnt/data/bitstamp_logs/reload_log > /dev/null
    endscript
}

then you can run it on background

nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4

$('#my-modal').on('hidden.bs.modal', function () {
  window.alert('hidden event fired!');
});

See this JSFiddle for a working example:

https://jsfiddle.net/6n7bg2c9/

See the Modal Events section of the docs here:

https://getbootstrap.com/docs/4.3/components/modal/#events

PHP str_replace replace spaces with underscores

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of:

$journalName = str_replace(' ', '_', $journalName);

How to remove jar file from local maven repository which was added with install:install-file?

Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/ directory if you are using a linux OS.

ORA-28000: the account is locked error getting frequently

I have faced this similar issue and resolved it by using following steps :

  1. Open windows command prompt.
  2. Login using the command sqlplus "/ as sysdba"
  3. Then executed the command alter user HR identified by password account unlock

    Please note, the password is the password that I have used.

    By using above steps you can connect to Oracle Database as user HR with the password password.

How can I check if a directory exists in a Bash shell script?

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi

This is not completely true...

If you want to go to that directory, you also need to have the execute rights on the directory. Maybe you need to have write rights as well.

Therefore:

if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
    # ... to go to that directory (even if DIRECTORY is a link)
    cd $DIRECTORY
    pwd
fi

if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
    # ... to go to that directory and write something there (even if DIRECTORY is a link)
    cd $DIRECTORY
    touch foobar
fi

Python 2.7 getting user input and manipulating as string without quotations

My Working code with fixes:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
     print("Correct!")
     correct = True
else:
    print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
        print("Correct!")
        correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

print("Thanks for playing!")

Accessing Object Memory Address

While it's true that id(object) gets the object's address in the default CPython implementation, this is generally useless... you can't do anything with the address from pure Python code.

The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.

MySQL create stored procedure syntax with delimiter

I have created a simple MySQL procedure as given below:

DELIMITER //
CREATE PROCEDURE GetAllListings()
 BEGIN
 SELECT nid, type, title  FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;

Kindly follow this. After the procedure created, you can see the same and execute it.

Way to get number of digits in an int?

Here's a really simple method I made that works for any number:

public static int numberLength(int userNumber) {

    int numberCounter = 10;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        int numberRatio = userNumber / numberCounter;
        if (numberRatio < 1) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }

    return digitLength; 
}

The way it works is with the number counter variable is that 10 = 1 digit space. For example .1 = 1 tenth => 1 digit space. Therefore if you have int number = 103342; you'll get 6, because that's the equivalent of .000001 spaces back. Also, does anyone have a better variable name for numberCounter? I can't think of anything better.

Edit: Just thought of a better explanation. Essentially what this while loop is doing is making it so you divide your number by 10, until it's less than one. Essentially, when you divide something by 10 you're moving it back one number space, so you simply divide it by 10 until you reach <1 for the amount of digits in your number.

Here's another version that can count the amount of numbers in a decimal:

public static int repeatingLength(double decimalNumber) {

    int numberCounter = 1;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        double numberRatio = decimalNumber * numberCounter;

        if ((numberRatio - Math.round(numberRatio)) < 0.0000001) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }
    return digitLength - 1;
}

css - position div to bottom of containing div

Add position: relative to .outside. (https://developer.mozilla.org/en-US/docs/CSS/position)

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

The "initial container" would be <body>, but adding the above makes .outside positioned.

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Replace words in a string - Ruby

First, you don't declare the type in Ruby, so you don't need the first string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

Moving Average Pandas

In case you are calculating more than one moving average:

for i in range(2,10):
   df['MA{}'.format(i)] = df.rolling(window=i).mean()

Then you can do an aggregate average of all the MA

df[[f for f in list(df) if "MA" in f]].mean(axis=1)

jQuery object equality

Since jQuery 1.6, you can use .is. Below is the answer from over a year ago...

var a = $('#foo');
var b = a;


if (a.is(b)) {
    // the same object!
}

If you want to see if two variables are actually the same object, eg:

var a = $('#foo');
var b = a;

...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.

if ($.data(a) == $.data(b)) {
    // the same object!
}

Though, the same could be achieved with a simple a === b, the above might at least show the next developer exactly what you're testing for.

In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:

$.fn.equals = function(compareTo) {
  if (!compareTo || this.length != compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

Source

var a = $('p');
var b = $('p');
if (a.equals(b)) {
    // same set
}

Why cannot cast Integer to String in java?

Use .toString instead like below:

String myString = myIntegerObject.toString();

Odd behavior when Java converts int to byte?

If you want to understand this mathematically, like how this works

so basically numbers b/w -128 to 127 will be written same as their decimal value, above that its (your number - 256).

eg. 132, the answer will be 132 - 256 = - 124 i.e.

256 + your answer in the number 256 + (-124) is 132

Another Example

double a = 295.04;
int b = 300;
byte c = (byte) a;
byte d = (byte) b; System.out.println(c + " " + d);

the Output will be 39 44

(295 - 256) (300 - 256)

NOTE: it won't consider numbers after the decimal.

How can I create a dynamic button click event on a dynamic button?

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

What do two question marks together mean in C#?

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

is equivalent to

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

But the cool thing about it is you can chain them, like other people said. The one thin not touched upon is that you can actually use it to throw an exception.

A = A ?? B ?? throw new Exception("A and B are both NULL");

How to use regex in file find

Use -regex:

From the man page:

-regex pattern
       File name matches regular expression pattern.  This is a match on the whole path, not a search.  For example, to match a file named './fubar3',  you  can  use  the
       regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.

Also, I don't believe find supports regex extensions such as \d. You need to use [0-9].

find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'

Popup window in PHP?

PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.

So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.

jQuery Toggle Text?

Perhaps I'm oversimplifying the problem, but this is what I use.

$.fn.extend({
    toggleText: function(a, b) {
        $.trim(this.html()) == a ? this.html(b) : this.html(a);
    }
});

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

Moving up one directory in Python

Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:

import os
os.chdir(os.path.dirname(os.getcwd()))

That gets the current working directory, steps up one directory, and then changes to that directory.

How to get StackPanel's children to fill maximum space downward?

It sounds like you want a StackPanel where the final element uses up all the remaining space. But why not use a DockPanel? Decorate the other elements in the DockPanel with DockPanel.Dock="Top", and then your help control can fill the remaining space.

XAML:

<DockPanel Width="200" Height="200" Background="PowderBlue">
    <TextBlock DockPanel.Dock="Top">Something</TextBlock>
    <TextBlock DockPanel.Dock="Top">Something else</TextBlock>
    <DockPanel
        HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" 
        Height="Auto" 
        Margin="10">

      <GroupBox 
        DockPanel.Dock="Right" 
        Header="Help" 
        Width="100" 
        Background="Beige" 
        VerticalAlignment="Stretch" 
        VerticalContentAlignment="Stretch" 
        Height="Auto">
        <TextBlock Text="This is the help that is available on the news screen." 
                   TextWrapping="Wrap" />
     </GroupBox>

      <StackPanel DockPanel.Dock="Left" Margin="10" 
           Width="Auto" HorizontalAlignment="Stretch">
          <TextBlock Text="Here is the news that should wrap around." 
                     TextWrapping="Wrap"/>
      </StackPanel>
    </DockPanel>
</DockPanel>

If you are on a platform without DockPanel available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:

<Grid Width="200" Height="200" Background="PowderBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
        <TextBlock>Something</TextBlock>
        <TextBlock>Something else</TextBlock>
    </StackPanel>
    <Grid Height="Auto" Grid.Row="1" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Width="100"
            Height="Auto"
            Grid.Column="1"
            Background="Beige"
            Header="Help">
            <TextBlock Text="This is the help that is available on the news screen." 
              TextWrapping="Wrap"/>
        </GroupBox>
        <StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
            <TextBlock Text="Here is the news that should wrap around." 
              TextWrapping="Wrap"/>
        </StackPanel>
    </Grid>
</Grid>

How to check if input date is equal to today's date?

The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.

var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)

The tilde truncs the division result (see this article about integer division)

How to move an element down a litte bit in html

<div class="row-2">
 <ul>
     <li><a href="index.html" class="active"><p style="margin-top: 10px;">Buy</p></a></li>
 </ul>

Play with it

Set initial focus in an Android application

@Someone Somewhere, I tried all of the above to no avail. The fix I found is from http://www.helloandroid.com/tutorials/remove-autofocus-edittext-android . Basically, you need to create an invisible layout just above the problematic Button:

<LinearLayout android:focusable="true"
              android:focusableInTouchMode="true" 
              android:layout_width="0px"
              android:layout_height="0px" >
    <requestFocus />
</LinearLayout>

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

It looks like you added a dependency on a Paypal library but did not include that library in your project:

Caused by: java.lang.ClassNotFoundException: com.paypal.exception.SSLConfigurationException

I'm not sure which jar, but it is most likely paypal-core.jar. Try adding it under WEB-INF/lib.