Programs & Examples On #Drawer

Same Navigation Drawer in different Activities

My answer is just a conceptual one without any source code. It might be useful for some readers like myself to understand.

It depends on your initial approach on how you architecture your app. There are basically two approaches.

  1. You create one activity (base activity) and all the other views and screens will be fragments. That base activity contains the implementation for Drawer and Coordinator Layouts. It is actually my preferred way of doing because having small self-contained fragments will make app development easier and smoother.

  2. If you have started your app development with activities, one for each screen , then you will probably create base activity, and all other activity extends from it. The base activity will contain the code for drawer and coordinator implementation. Any activity that needs drawer implementation can extend from base activity.

I would personally prefer avoiding to use fragments and activities mixed without any organizing. That makes the development more difficult and get you stuck eventually. If you have done it, refactor your code.

Why docker container exits immediately

A docker container exits when its main process finishes.

In this case it will exit when your start-all.sh script ends. I don't know enough about hadoop to tell you how to do it in this case, but you need to either leave something running in the foreground or use a process manager such as runit or supervisord to run the processes.

I think you must be mistaken about it working if you don't specify -d; it should have exactly the same effect. I suspect you launched it with a slightly different command or using -it which will change things.

A simple solution may be to add something like:

while true; do sleep 1000; done

to the end of the script. I don't like this however, as the script should really be monitoring the processes it kicked off.

(I should say I stole that code from https://github.com/sequenceiq/hadoop-docker/blob/master/bootstrap.sh)

trigger body click with jQuery

I've used the following code a few times and it works sweet:

$("body").click(function(e){ 
    // Check what has been clicked:
    var target = $(e.target); 
    if(target.is("#target")){
    // The target was clicked
    // Do something...
  }
});

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Fail module works great! Thanks.

I had to define my fact before checking it, otherwise I'd get an undefined variable error.

And I had issues when doing setting the fact with quotes and without spaces.

This worked:

set_fact: flag="failed"

This threw errors:

set_fact: flag = failed 

How to access session variables from any class in ASP.NET?

In asp.net core this works differerently:

public class SomeOtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void TestSet()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public void TestGet()
    {
        var message = _session.GetString("Test");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

Adding custom HTTP headers using JavaScript

As already said, the easiest way is to use querystring.

But if you cannot, because of security reason, you should consider using cookies.

Adobe Reader Command Line Reference

To open a PDF at page 100 the follow works

<path to Adobe Reader> /A "page=100" "<Path To PDF file>"

If you require more than one argument separate them with &

I use the following in a batch file to open the book I'm reading to the page I was up to.

C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"

The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf

It's for version 7 but all the arguments I tried worked.

As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.

Generate random 5 characters string

Here are my random 5 cents ...

$random=function($a, $b) {
    return(
        substr(str_shuffle(('\\`)/|@'.
        password_hash(mt_rand(0,999999),
        PASSWORD_DEFAULT).'!*^&~(')),
        $a, $b)
    );
};

echo($random(0,5));

PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.

Two concat. strings before and after password_hash within $random function are suitable for change.

Paramteres for $random() *($a,$b) are actually substr() parameters. :)

NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:

$random=(substr(str_shuffle(('\\`)/|@'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));

echo($random);

What ports does RabbitMQ use?

To find out what ports rabbitmq uses:

$ epmd -names

Outputs:

epmd: up and running on port 4369 with data:
name rabbit at port 25672

Run these as root:

lsof -i :4369
lsof -i :25672

More about epmd options.

Intercept page exit event

Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

parsing JSONP $http.jsonp() response in angular.js

You still need to set callback in the params:

var params = {
  'a': b,
  'token_auth': TOKEN,
  'callback': 'functionName'
};
$sce.trustAsResourceUrl(url);

$http.jsonp(url, {
  params: params
});

Where 'functionName' is a stringified reference to globally defined function. You can define it outside of your angular script and then redefine it in your module.

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

How to make readonly all inputs in some div in Angular2?

Try this in input field:

[readonly]="true"

Hope, this will work.

How to obtain the last path segment of a URI

I'm using the following in a utility class:

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
    return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
    return uri.toString().contains("/")
        ? (ellipsis.length == 0 ? "..." : ellipsis[0])
          + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
        : uri.toString();
}

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

pandas unique values multiple columns

for those of us that love all things pandas, apply, and of course lambda functions:

df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() etc. you can use the code below:

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

How to get domain URL and application name?

I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Bootstrap Carousel image doesn't align properly

I am facing the same problem with you. Based on the hint of @thuliha, the following codes has solved my issues.

In the html file, modify as the following sample:

<img class="img-responsive center-block" src=".....png" alt="Third slide">

In the carousel.css, modify the class:

.carousel .item {
  text-align: center;
  height: 470px;
  background-color: #777;
}

What is the difference between Cloud Computing and Grid Computing?

A Grid is a hardware and software infrastructure that clusters and integrates high-end computers, networks, databases, and scientific instruments from multiple sources to form a virtual supercomputer on which users can work collaboratively within virtual organisations

Grid is Mostly free used by academic research etc.

Clouds are a large pool of easily usable and accessible virtualized resources (such as hardware, development platforms and/or services). These resources can be dynamically reconfigured to adjust to a variable load (scale), allowing also for an optimum resource utilization. This pool of resources is typically exploited by a pay peruse model in which guarantees are offered by the Infrastructure Provider by customized service level agreements.

Cloud is not free. It is a service, provided by different service providers and they charge according to your work done.

Name node is in safe mode. Not able to leave

Run the command below using the HDFS OS user to disable safe mode:

sudo -u hdfs hadoop dfsadmin -safemode leave

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

git pull from master into the development branch

Situation: Working in my local branch, but I love to keep-up updates in the development branch named dev.

Solution: Usually, I prefer to do :

git fetch
git rebase origin/dev

How to delete all files and folders in a folder by cmd call

Yes! Use Powershell:

powershell -Command "Remove-Item 'c:\destination\*' -Recurse -Force"

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

Asynchronous method call in Python?

You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The multiprocessing module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.

from inspect import getmodule
from multiprocessing import Pool


def async(decorated):
    r'''Wraps a top-level function around an asynchronous dispatcher.

        when the decorated function is called, a task is submitted to a
        process pool, and a future object is returned, providing access to an
        eventual return value.

        The future object has a blocking get() method to access the task
        result: it will return immediately if the job is already done, or block
        until it completes.

        This decorator won't work on methods, due to limitations in Python's
        pickling machinery (in principle methods could be made pickleable, but
        good luck on that).
    '''
    # Keeps the original function visible from the module global namespace,
    # under a name consistent to its __name__ attribute. This is necessary for
    # the multiprocessing pickling machinery to work properly.
    module = getmodule(decorated)
    decorated.__name__ += '_original'
    setattr(module, decorated.__name__, decorated)

    def send(*args, **opts):
        return async.pool.apply_async(decorated, args, opts)

    return send

The code below illustrates usage of the decorator:

@async
def printsum(uid, values):
    summed = 0
    for value in values:
        summed += value

    print("Worker %i: sum value is %i" % (uid, summed))

    return (uid, summed)


if __name__ == '__main__':
    from random import sample

    # The process pool must be created inside __main__.
    async.pool = Pool(4)

    p = range(0, 1000)
    results = []
    for i in range(4):
        result = printsum(i, sample(p, 100))
        results.append(result)

    for result in results:
        print("Worker %i: sum value is %i" % result.get())

In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.

Automatically scroll down chat div

Let's review a few useful concepts about scrolling first:

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;
}

Full chat simulator (with JavaScript):

https://jsfiddle.net/apvtL9xa/

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Which font is used in Visual Studio Code Editor and how to change fonts?

In the default settings, VS Code uses the following fonts (14 pt) in descending order:

  • Monaco
  • Menlo
  • Consolas
  • "Droid Sans Mono"
  • "Inconsolata"
  • "Courier New"
  • monospace (fallback)

How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.

relevant areas

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

Finding longest string in array

Maybe not the fastest, but certainly pretty readable:

function findLongestWord(array) {
  var longestWord = "";

  array.forEach(function(word) {
    if(word.length > longestWord.length) {
      longestWord = word;
    }
  });

  return longestWord;
}

var word = findLongestWord(["The","quick","brown", "fox", "jumped", "over", "the", "lazy", "dog"]);
console.log(word); // result is "jumped"

The array function forEach has been supported since IE9+.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

How to print the value of a Tensor object in TensorFlow?

I didn't find it easy to understand what is required even after reading all the answers until I executed this. TensofFlow is new to me too.

def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(b))
    sess.close()

But still you may need the value returned by executing the session.

def printtest():
    x = tf.constant([100.0])
    x = tf.Print(x,[x],message="Test")
    init = (tf.global_variables_initializer(), tf.local_variables_initializer())
    b = tf.add(x, x)
    with tf.Session() as sess:
        sess.run(init)
        c = sess.run(b)
        print(c)
        sess.close()

How to control the width of select tag?

Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

It's very very easy in Gnu/Linux - Mac - Windows

First: - copy this command

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android 

Second: Now copy and paste the command in the terminal the Android Studio enter image description here

Result!

enter image description here

Good Luck!!

How to set custom ActionBar color / style?

Custom Color:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

                <item name="colorPrimary">@color/ColorPrimary</item>
                <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
                <!-- Customize your theme here. -->
     </style>

Custom Style:

 <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>

For More: Android ActionBar

Making TextView scrollable on Android

If you don't want to use the EditText solution then you might have better luck with:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yourLayout);
    (TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}

Indenting code in Sublime text 2?

This is my configuration for sublime-keymap:

[
  {
    "keys": [",+=+="],
    "command": "reindent",
    "args": {
      "single_line": false
    }
  }
]

For vim people, just use ,== to reindent the whole file.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Nothing built in, my solution would be as follows :

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

Working example

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  function tConvert(time) {_x000D_
    // Check correct time format and split into components_x000D_
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
_x000D_
    if (time.length > 1) { // If time format correct_x000D_
      time = time.slice(1); // Remove full string match value_x000D_
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
      time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
    }_x000D_
    return time.join(''); // return adjusted time or original string_x000D_
  }_x000D_
_x000D_
  var tel = document.getElementById('tests');_x000D_
_x000D_
  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {_x000D_
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;_x000D_
  }).join('\n');_x000D_
})();
_x000D_
<h3>tConvert tests : </h3>_x000D_
<pre id="tests">_x000D_
  18:00:00_x000D_
  18:00_x000D_
  00:00_x000D_
  11:59:01_x000D_
  12:00:00_x000D_
  13:01:57_x000D_
  24:00_x000D_
  sdfsdf_x000D_
  12:61:54_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Hadoop: «ERROR : JAVA_HOME is not set»

In some distributives(CentOS/OpenSuSe,...) will work only if you set JAVA_HOME in the /etc/environment.

SVN - Checksum mismatch while updating

I had a simllar problem. Main provider was antivirus "FortiClient" (antivirus + VPN CLient). When I disabled it - all update/checkout was made correctly

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

how to end ng serve or firebase serve

----Ctrl + c then choose Y from the Y/N option provided.

What is the best way to dump entire objects to a log in C#?

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

Detect when an image fails to load in Javascript

The answer is nice, but it introduces one problem. Whenever you assign onload or onerror directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.

Let me rewrite the answer a little bit.

function testImage(url) {
    var tester = new Image();
    tester.addEventListener('load', imageFound);
    tester.addEventListener('error', imageNotFound);
    tester.src = url;
}

function imageFound() {
    alert('That image is found and loaded');
}

function imageNotFound() {
    alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.

function testImage(url) {

    // Define the promise
    const imgPromise = new Promise(function imgPromise(resolve, reject) {

        // Create the image
        const imgElement = new Image();

        // When image is loaded, resolve the promise
        imgElement.addEventListener('load', function imgOnLoad() {
            resolve(this);
        });

        // When there's an error during load, reject the promise
        imgElement.addEventListener('error', function imgOnError() {
            reject();
        })

        // Assign URL
        imgElement.src = url;

    });

    return imgPromise;
}

testImage("http://foo.com/bar.jpg").then(

    function fulfilled(img) {
        console.log('That image is found and loaded', img);
    },

    function rejected() {
        console.log('That image was not found');
    }

);

How to set a default value for an existing column

First drop constraints

https://stackoverflow.com/a/49393045/2547164

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

Second create default value

ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

Input placeholders for Internet Explorer

i use jquery.placeholderlabels. It's based on this and can be demoed here.

works in ie7, ie8, ie9.

behavior mimics current firefox and chrome behavior - where the the "placeholder" text remains visible on focus and only disappears once something is typed in the field.

Export DataTable to Excel File

Below link is used to export datatable to excel in C# Code.

http://royalarun.blogspot.in/2012/01/export-datatable-to-excel-in-c-windows.html

  using System;      
   using System.Data;  
   using System.IO;  
   using System.Windows.Forms;  

    namespace ExportExcel  
    {      
        public partial class ExportDatatabletoExcel : Form  
        {  
            public ExportDatatabletoExcel()  
            {  
                InitializeComponent();  
            }  

            private void Form1_Load(object sender, EventArgs e)
            {

                DataTable dt = new DataTable();

                //Add Datacolumn
                DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));

                dt.Columns.Add("LastName", typeof(String));
                dt.Columns.Add("Blog", typeof(String));
                dt.Columns.Add("City", typeof(String));
                dt.Columns.Add("Country", typeof(String));

                //Add in the datarow
                DataRow newRow = dt.NewRow();

                newRow["firstname"] = "Arun";
                newRow["lastname"] = "Prakash";
                newRow["Blog"] = "http://royalarun.blogspot.com/";
                newRow["city"] = "Coimbatore";
                newRow["country"] = "India";

                dt.Rows.Add(newRow);

                //open file
                StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");

                try
                {

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
                    }

                    wr.WriteLine();

                    //write rows to excel file
                    for (int i = 0; i < (dt.Rows.Count); i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (dt.Rows[i][j] != null)
                            {
                                wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                            }
                            else
                            {
                                wr.Write("\t");
                            }
                        }
                        //go to next line
                        wr.WriteLine();
                    }
                    //close file
                    wr.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

Get specific objects from ArrayList when objects were added anonymously?

You could use list.indexOf(Object) bug in all honesty what you're describing sounds like you'd be better off using a Map.

Try this:

Map<String, Object> mapOfObjects = new HashMap<String, Object>();
mapOfObjects.put("objectName", object);

Then later when you want to retrieve the object, use

mapOfObjects.get("objectName");

Assuming you do know the object's name as you stated, this will be both cleaner and will have faster performance besides, particularly if the map contains large numbers of objects.

If you need the objects in the Map to stay in order, you can use

Map<String, Object> mapOfObjects = new LinkedHashMap<String, Object>();

instead

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

copy-item With Alternate Credentials

This question addresses a very related issue that may help using network shares in powershell.

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.

How do I assert my exception message with JUnit Test annotation?

Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.

Add this utility class:

import org.junit.Assert;

public abstract class ExpectedRuntimeExceptionAsserter {

    private String expectedExceptionMessage;

    public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
        this.expectedExceptionMessage = expectedExceptionMessage;
    }

    public final void run(){
        try{
            expectException();
            Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
        } catch (RuntimeException e){
            Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
        }
    }

    protected abstract void expectException();

}

Then for my unit test, all I need is this code:

@Test
public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
    new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
        @Override
        protected void expectException() {
            throw new RuntimeException("anonymous user can't access privileged resource");
        }
    }.run(); //passes test; expected exception is caught, and this @Test returns normally as "Passed"
}

PHPMailer character encoding issues

$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "16bit";

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

How to backup Sql Database Programmatically in C#

I have new method without SMO problems

1. Create .bat File with backup sqlcmd command

for backup

SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”

for restore

SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”

2. Run the the bat file with WPF/C# code

        FileInfo file = new FileInfo("DB\\batfile.bat");
        Process process = new Process();
        process.StartInfo.FileName = file.FullName;
        process.StartInfo.Arguments = @"-X";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        process.StartInfo.UseShellExecute = false; //Changed Line
        process.StartInfo.RedirectStandardOutput = true;  //Changed Line
        process.Start();
        string output = process.StandardOutput.ReadToEnd(); //Changed Line
        process.WaitForExit(); //Moved Line

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

Under what conditions is a JSESSIONID created?

For links generated in a JSP with custom tags, I had to use

<%@ page session="false" %>

in the JSP

AND

request.getSession().invalidate();

in the Struts action

How to add 10 days to current time in Rails

Try this on Ruby. It will return a new date/time the specified number of days in the future

DateTime.now.days_since(10)

How do I change the text of a span element using JavaScript?

For some reason, it seems that using "text" attribute is the way to go with most browsers. It worked for me

$("#span_id").text("text value to assign");

An unhandled exception was generated during the execution of the current web request

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

Foreach loop in java for a custom object list

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Here is one way to do it. Involves doing a little PHP as well.

The PHP part:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);

The jQuery part:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });

So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

Had some help on the php part from 1

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

In AVD emulator how to see sdcard folder? and Install apk to AVD?

DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

Easiest way to compare arrays in C#

SequenceEqual will only return true if two conditions or met.

  1. They contain the same elements.
  2. The elements are in the same order.

If you only want to check if they contain the same elements regardless of their order and your problem is of the type

Does values2 contain all the values contained in values1?

you can use LINQ extension method Enumerable.Except and then check if the result has any value. Here's an example

int[] values1 = { 1, 2, 3, 4 };
int[] values2 = { 1, 2, 5 };
var result = values1.Except(values2);
if(result.Count()==0)
{
   //They are the same
}
else
{
    //They are different
}

And also by using this you get the different items as well automatically. Two birds with one stone.

Keep in mind, if you execute your code like this

var result = values2.Except(values1);

you will get different results.

In my case I have a local copy of an array and want to check if anything has been removed from the original array so I use this method.

Remove lines that contain certain string

Regex is a little quicker than the accepted answer (for my 23 MB test file) that I used. But there isn't a lot in it.

import re

bad_words = ['bad', 'naughty']

regex = f"^.*(:{'|'.join(bad_words)}).*\n"
subst = ""

with open('oldfile.txt') as oldfile:
    lines = oldfile.read()

result = re.sub(regex, subst, lines, re.MULTILINE) 

with open('newfile.txt', 'w') as newfile:
    newfile.write(result)

enter image description here

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

By default Vagrant uses a generated private key to login, you can try this:

ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

When to Redis? When to MongoDB?

If your project budged allows you to have enough RAM memory on your environment - answer is Redis. Especially taking in account new Redis 3.2 with cluster functionality.

How can I get the height and width of an uiimage?

UIImage *img = [UIImage imageNamed:@"logo.png"];

CGFloat width = img.size.width;
CGFloat height = img.size.height;

How to post data to specific URL using WebClient in C#

Using simple client.UploadString(adress, content); normally works fine but I think it should be remembered that a WebException will be thrown if not a HTTP successful status code is returned. I usually handle it like this to print any exception message the remote server is returning:

try
{
    postResult = client.UploadString(address, content);
}
catch (WebException ex)
{
    String responseFromServer = ex.Message.ToString() + " ";
    if (ex.Response != null)
    {
        using (WebResponse response = ex.Response)
        {
            Stream dataRs = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(dataRs))
            {
                responseFromServer += reader.ReadToEnd();
                _log.Error("Server Response: " + responseFromServer);
            }
        }
    }
    throw;
}

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.

I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.

Forbidden :You don't have permission to access /phpmyadmin on this server

On a fresh install on CENTOS7 I have tried the above methods (edit phpMyAdmin.conf and add Require all granted), it still does'nt work. Here is the solution : install the mod_php module :

$ sudo yum install php

then restart httpd :

$ sudo systemctl restart httpd

and voila !

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

Below code may help you to achieve session attribution inside java script:

var name = '<%= session.getAttribute("username") %>';

REST API using POST instead of GET

Just to review, REST has certain properties that a developer should follow in order to make it RESTful:

What is REST?

According to wikipedia:

The REST architectural style describes the following six constraints applied to the architecture, while leaving the implementation of the individual components free to design:

  • Client–server: Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable.
  • Stateless: The client–server communication is further constrained by no client context being stored on the server between requests.
  • Cacheable: Responses must, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests.
  • Layered system: A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
  • Code on demand (optional): Servers can temporarily extend or customize the functionality of a client by the transfer of executable code.
  • Uniform interface: The uniform interface between clients and servers, discussed below, simplifies and decouples the architecture, which enables each part to evolve independently. (i.e. HTTP GET, POST, PUT, PATCH, DELETE)

What the verbs should do

SO user Daniel Vasallo did a good job of laying out the responsibilities of these methods in the question Understanding REST: Verbs, error codes, and authentication:

When dealing with a Collection URI like: http://example.com/resources/

GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

PUT: Meaning defined as "replace the entire collection with another collection".

POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

DELETE: Meaning defined as "delete the entire collection".

So, to answer your question:

Is it right to say that I can use it with a POST query? ...

Are these two queries the same? Can I use the second variant in any case or the documentation should explicitly say that I can use both GET and POST queries?

If you were writing a plain old RPC API call, they could technically interchangeable as long as the processing server side were no different between both calls. However, in order for the call to be RESTful, calling the endpoint via the GET method should have a distinct functionality (which is to get resource(s)) from the POST method (which is to create new resources).

Side note: there is some debate out there about whether or not POST should also be allowed to be used to update resources... though i'm not commenting on that, I'm just telling you some people have an issue with that point.

Gson - convert from Json to a typed ArrayList<T>

Kotlin

data class Player(val name : String, val surname: String)

val json = [
  {
    "name": "name 1",
    "surname": "surname 1"
  },
  {
    "name": "name 2",
    "surname": "surname 2"
  },
  {
    "name": "name 3",
    "surname": "surname 3"
  }
]

val typeToken = object : TypeToken<List<Player>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)

OR

val playerArray = Gson().fromJson(json, Array<Player>::class.java)

gridview data export to excel in asp.net

Instead of doing all these.. cant you use a simpler approach as shown below.

Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

You can get the entire walkthrough here

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

How to set the height and the width of a textfield in Java?

There's a way which maybe not perfect, but can meet your requirement. The main point here is use a special dimension to restrict the height. But at the same time, width actually is free, as the max width is big enough.

package test;
import java.awt.*;
import javax.swing.*;

public final class TestFrame extends Frame{
    public TestFrame(){
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setPreferredSize(new Dimension(500, 200));
        p.setMaximumSize(new Dimension(10000, 200));
        p.add(new JLabel("TEST: "));

        JPanel p1 = new JPanel();
        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
        p1.setMaximumSize(new Dimension(10000, 200));
        p1.add(new JTextField(50));

        p.add(p1);

        this.setLayout(new BorderLayout());
        this.add(p, BorderLayout.CENTER);
    }
    //TODO: GUI CREATE
}

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

Copy Image from Remote Server Over HTTP

PHP has a built-in function file_get_contents(), which reads the content of a file into a string.

<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");

//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?>

If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

How do I turn a String into a InputStreamReader in java?

Same question as @Dan - why not StringReader ?

If it has to be InputStreamReader, then:

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

Throw keyword in function's signature

Well, while googling about this throw specification, I had a look at this article :- (http://blogs.msdn.com/b/larryosterman/archive/2006/03/22/558390.aspx)

I am reproducing a part of it here also, so that it can be used in future irrespective of the fact that the above link works or not.

   class MyClass
   {
    size_t CalculateFoo()
    {
        :
        :
    };
    size_t MethodThatCannotThrow() throw()
    {
        return 100;
    };
    void ExampleMethod()
    {
        size_t foo, bar;
        try
        {
            foo = CalculateFoo();
            bar = foo * 100;
            MethodThatCannotThrow();
            printf("bar is %d", bar);
        }
        catch (...)
        {
        }
    }
};

When the compiler sees this, with the "throw()" attribute, the compiler can completely optimize the "bar" variable away, because it knows that there is no way for an exception to be thrown from MethodThatCannotThrow(). Without the throw() attribute, the compiler has to create the "bar" variable, because if MethodThatCannotThrow throws an exception, the exception handler may/will depend on the value of the bar variable.

In addition, source code analysis tools like prefast can (and will) use the throw() annotation to improve their error detection capabilities - for example, if you have a try/catch and all the functions you call are marked as throw(), you don't need the try/catch (yes, this has a problem if you later call a function that could throw).

Laravel Request getting current path with query string

Laravel 4.5

Just use

Request::fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace(Request::url(), '', Request::fullUrl())

Or you can get a array of all the queries with

Request::query()

Laravel >5.1

Just use

$request->fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace($request->url(), '',$request->fullUrl())

Or you can get a array of all the queries with

$request->query()

YAML equivalent of array of objects in JSON

TL;DR

You want this:

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

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.

JSON to YAML

Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

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

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

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

Parsing this and converting it back to JSON yields the expected result:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

There are No resources that can be added or removed from the server

The issue is it is missing Dynamic Web Module facet definition. Run the following at command line

mvn eclipse:eclipse -Dwtpversion=2.0

After build is success, refresh the project and you will be add the web project to server.

Tuple unpacking in for loops

Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

I created some test code to demonstrate this:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

The simplicity of Tuple unpacking is probably one of my favourite things about Python :D

How do I remove duplicates from a C# array?

using System;
using System.Collections.Generic;
using System.Linq;


namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
             List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };
           List<int> updatedlist= removeduplicate(listofint1);
            foreach(int num in updatedlist)
               Console.WriteLine(num);
        }


        public static List<int> removeduplicate(List<int> listofint)
         {
             List<int> listofintwithoutduplicate= new List<int>();


              foreach(var num in listofint)
                 {
                  if(!listofintwithoutduplicate.Any(p=>p==num))
                        {
                          listofintwithoutduplicate.Add(num);
                        }
                  }
             return listofintwithoutduplicate;
         }
    }



}

Setting a timeout for socket operations

You can't control the timeout due to UnknownHostException. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.

But I find it hard to believe that you are really getting an UnknownHostException when you specify an IP address rather than a hostname.

EDIT To control Java's DNS timeouts see this answer.

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

ignoring any 'bin' directory on a git project

As a notice;

If you think about .gitignore does not work in a way (so added foo/* folder in it but git status still showing that folder content(s) as modified or something like this), then you can use this command;

git checkout -- foo/*

Adding a Method to an Existing Object Instance

from types import MethodType

def method(self):
   print 'hi!'


setattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )

With this, you can use the self pointer

JavaScript alert not working in Android WebView

As others indicated, setting the WebChromeClient is needed to get alert() to work. It's sufficient to just set the default WebChromeClient():

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient());

Thanks for all the comments below. Including John Smith's who indicated that you needed to enable JavaScript.

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

Unable to open project... cannot be opened because the project file cannot be parsed

Muhammad's answer was very helpful (and helped lead to my fix). However, simply removing the >>>>>>> ======= <<<<<<< wasn't enough to fix the parse issue in the project.pbxproj (for me) when keeping changes from both branches after a merge.

I had a merge conflict in the PBXGroup section (whose beginning is indicated by a block comment like this: /* Begin PBXGroup section */) of the project.pbxproj file. However, the problem I encountered can occur in other places in the project.pbxproj file as well.

Below is a simplification of the merge conflict I encountered:

    <<<<<<< HEAD
          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
    =======
          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
    >>>>>>> branch name
            sourceTree = "<group>";
          };

When i removed the merge conflict markers this is what I was left with:

          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
            sourceTree = "<group>";
          };

Normally, removing the merge conflict markers would fix the parse issue in the project.pbxproj file and restore the workspace integrity. This time it didn't.

Below is what I did to solve the issue:

          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
            sourceTree = "<group>";
          };

          id = {
            isa = PBXGroup;
            children = (
                 id
            );
            name = "Your Group Name";
            sourceTree = "<group>";
          };

I actually had to add 2 lines at the end of the first PBXGroup.

You can see that if I would have chosen to discard the changes from either Head or the merging branch, there wouldn't have been a parse issue! However, in my case I wanted to keep both groups I added from each branch and simply removing the merge markers wasn't enough; I had to add extra lines to the project.pbxproj file in order to maintain correct formatting.

So, if you're running into parsing issues after you thought you'd resolved all you're merge conflicts, you might want to take a closer look at the .pbxproj and make sure there aren't any formatting problems!

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

PHP FPM - check if running

For php7.0-fpm I call:

service php7.0-fpm status

php7.0-fpm start/running, process 25993

Now watch for the good part. The process name is actually php-fpm7.0

echo `/bin/pidof php-fpm7.0`

26334 26297 26286 26285 26282

How do I "commit" changes in a git submodule?

You can treat a submodule exactly like an ordinary repository. To propagate your changes upstream just commit and push as you would normally within that directory.

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

you could also go to Hardware -> reboot, then Hardware -> Home, and click on your App

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

What's the "average" requests per second for a production web application?

Not sure anyone is still interested, but this information was posted about Twitter (and here too):

The Stats

  • Over 350,000 users. The actual numbers are as always, very super super top secret.
  • 600 requests per second.
  • Average 200-300 connections per second. Spiking to 800 connections per second.
  • MySQL handled 2,400 requests per second.
  • 180 Rails instances. Uses Mongrel as the "web" server.
  • 1 MySQL Server (one big 8 core box) and 1 slave. Slave is read only for statistics and reporting.
  • 30+ processes for handling odd jobs.
  • 8 Sun X4100s.
  • Process a request in 200 milliseconds in Rails.
  • Average time spent in the database is 50-100 milliseconds.
  • Over 16 GB of memcached.

Getting return value from stored procedure in C#

retval.Direction = ParameterDirection.Output;

ParameterDirection.ReturnValue should be used for the "return value" of the procedure, not output parameters. It gets the value returned by the SQL RETURN statement (with the parameter named @RETURN_VALUE).

Instead of RETURN @b you should SET @b = something

By the way, return value parameter is always int, not string.

How do I escape only single quotes?

I am not sure what exactly you are doing with your data, but you could always try:

$string = str_replace("'", "%27", $string);

I use this whenever strings are sent to a database for storage.

%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.

To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.

Happy injection avoiding!

How to add content to html body using JS?

You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

Try replacing <%# Eval("item") %> with <%# If(Eval("item"), "0 value") %> (or <%# Eval("item") ?? "0 value" %>, when using C#).

How to apply style classes to td classes?

When using with a reactive bootstrap table, i did not find that the

table.classname td {

syntax worked as there was no <table> tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead> and <tbody> for grouping at most.

Simply specifying like this worked great though

td.classname {
    max-width: 500px;
    text-overflow: initial;
    white-space: wrap;
    word-wrap: break-word;
}

as it directly overrides the <td> and can be used only on the elements you want to change. Maybe in your case use

thead.medium td {
  font-size: 40px; 
}
tbody.small td {
  font-size:25px;
}

for consistent font sizing with a bigger header.

how to display full stored procedure code?

SELECT prosrc FROM pg_proc WHERE proname = 'function_name';

This tells the function handler how to invoke the function. It might be the actual source code of the function for interpreted languages, a link symbol, a file name, or just about anything else, depending on the implementation language/call convention

Output of git branch in tree like fashion

Tested on Ubuntu:

sudo apt install git-extras
git-show-tree

This produces an effect similar to the 2 most upvoted answers here.

Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html


Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch or manually via git branch --set-upstream-to=upstream_branch).

Bonus git tricks:

Related:

  1. What's the difference between `arc graft` and `arc patch`?

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Simple and clean way to convert JSON string to Object in Swift

I like RDC's response, but why limit the JSON returned to have only arrays at the top level? I needed to allow a dictionary at the top level, so I modified it thus:

extension String
{
    var parseJSONString: AnyObject?
    {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        if let jsonData = data
        {
            // Will return an object or nil if JSON decoding fails
            do
            {
                let message = try NSJSONSerialization.JSONObjectWithData(jsonData, options:.MutableContainers)
                if let jsonResult = message as? NSMutableArray {
                    return jsonResult //Will return the json array output
                } else if let jsonResult = message as? NSMutableDictionary {
                    return jsonResult //Will return the json dictionary output
                } else {
                    return nil
                }
            }
            catch let error as NSError
            {
                print("An error occurred: \(error)")
                return nil
            }
        }
        else
        {
            // Lossless conversion of the string was not possible
            return nil
        }
    }

Confirm postback OnClientClick button ASP.NET

Using jQuery UI dialog:

SCRIPT:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
 $(function () {

            $("#<%=btnUserDelete.ClientID%>").on("click", function (event) {
                event.preventDefault();
                $("#dialog-confirm").dialog({
                    resizable: false,
                    height: 140,
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                            __doPostBack($('#<%= btnUserDelete.ClientID %>').attr('name'), '');
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            });
 });
</script>

HTML:

<div id="dialog-confirm" style="display: none;" title="Confirm Delete">
    <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure you want to delete this user?</p>
</div>

How can I use a C++ library from node.js?

There newer ways to connect Node.js and C++. Please, loot at Nan.

EDIT The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker class from nan.

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

How to change a nullable column to not nullable in a Rails migration?

Per the Strong Migrations gem, using change_column_null in production is a bad idea because it blocks reads and writes while all records are checked.

The recommended way to handle these migrations (Postgres specific) is to separate this process into two migrations.

One to alter the table with the constraint:

class SetSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" ADD CONSTRAINT "users_some_column_null" CHECK ("some_column" IS NOT NULL) NOT VALID'
    end
  end
end

And a separate migration to validate it:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end
  end
end

The above examples are pulled (and slightly altered) from the linked documentation. Apparently for Postgres 12+ you can also add NOT NULL to the schema and then drop the constraint after the validation has been run:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end

    # in Postgres 12+, you can then safely set NOT NULL on the column
    change_column_null :users, :some_column, false
    safety_assured do
      execute 'ALTER TABLE "users" DROP CONSTRAINT "users_some_column_null"'
    end
  end
end

Naturally, this means your schema will not show that the column is NOT NULL for earlier versions of Postgres, so I'd also advise setting a model level validation to require the value to be present (though I'd suggest the same even for versions of PG that do allow this step).

Further, before running these migrations you'll want to update all existing records with a value other than null, and make sure any production code that writes to the table is not writing null for the value(s).

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

Since glibc version 2.17, the library linking -lrt is no longer required.

The clock_* are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:

+* The `clock_*' suite of functions (declared in <time.h>) is now available
+  directly in the main C library.  Previously it was necessary to link with
+  -lrt to use these functions.  This change has the effect that a
+  single-threaded program that uses a function such as `clock_gettime' (and
+  is not linked with -lrt) will no longer implicitly load the pthreads
+  library at runtime and so will not suffer the overheads associated with
+  multi-thread support in other code such as the C++ runtime library.

If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.

To check the glibc version installed on the system, run the command:

ldd --version

(Of course, if you are using old glibc (<2.17) then you will still need -lrt.)

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

Search for an item in a Lua list

Lua tables are more closely analogs of Python dictionaries rather than lists. The table you have create is essentially a 1-based indexed array of strings. Use any standard search algorithm to find out if a value is in the array. Another approach would be to store the values as table keys instead as shown in the set implementation of Jon Ericson's post.

How do I get the HTTP status code with jQuery?

I encapsulate the jQuery Ajax to a method:

var http_util = function (type, url, params, success_handler, error_handler, base_url) {

    if(base_url) {
        url = base_url + url;
    }

    var success = arguments[3]?arguments[3]:function(){};
    var error = arguments[4]?arguments[4]:function(){};



    $.ajax({
        type: type,
        url: url,
        dataType: 'json',
        data: params,
        success: function (data, textStatus, xhr) {

            if(textStatus === 'success'){
                success(xhr.code, data);   // there returns the status code
            }
        },
        error: function (xhr, error_text, statusText) {

            error(xhr.code, xhr);  // there returns the status code
        }
    })

}

Usage:

http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
    console(status_code, data)
}, function(status_code, err){
    console(status_code, err)
})

How do I turn a C# object into a JSON string in .NET?

You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

How to install bcmath module?

yum install php72-php-bcmath.x86_64
cp /etc/opt/remi/php72/php.d/20-bcmath.ini /etc/php.d/
cp /opt/remi/php72/root/usr/lib64/php/modules/bcmath.so /usr/lib64/php/modules/
systemctl restart httpd

Not sure why I had to go so deep considering the yum install gave me bcmath in phpinfo()

How do you get the length of a string?

The easiest way:

$('#selector').val().length

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

What is the best JavaScript code to create an img element

Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);

Converting a sentence string to a string array of words in Java

Use string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ') to split your code into an array with no periods, commas, question marks, or exclamation marks. You can add/remove as many replace calls as you want.

How to use XMLReader in PHP?

The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:

$xml_reader = new XMLReader;
$xml_reader->open($feed_url);

// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');

// loop through the products
while ($xml_reader->name == 'product')
{
    // load the current xml element into simplexml and we’re off and running!
    $xml = simplexml_load_string($xml_reader->readOuterXML());

    // now you can use your simpleXML object ($xml).
    echo $xml->element_1;

    // move the pointer to the next product
    $xml_reader->next('product');
}

// don’t forget to close the file
$xml_reader->close();

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x.

What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator:

  • The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).

  • The connection is "bidirectional" in the sense that data can be both sent from and to a generator.

(If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)

BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.

Reading data from a generator using yield from

def reader():
    """A generator that fakes a read from a file, socket, etc."""
    for i in range(4):
        yield '<< %s' % i

def reader_wrapper(g):
    # Manually iterate over data produced by reader
    for v in g:
        yield v

wrap = reader_wrapper(reader())
for i in wrap:
    print(i)

# Result
<< 0
<< 1
<< 2
<< 3

Instead of manually iterating over reader(), we can just yield from it.

def reader_wrapper(g):
    yield from g

That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.

Sending data to a generator (coroutine) using yield from - Part 1

Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc.

def writer():
    """A coroutine that writes data *sent* to it to fd, socket, etc."""
    while True:
        w = (yield)
        print('>> ', w)

Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()?

def writer_wrapper(coro):
    # TBD
    pass

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in range(4):
    wrap.send(i)

# Expected result
>>  0
>>  1
>>  2
>>  3

The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works.

def writer_wrapper(coro):
    coro.send(None)  # prime the coro
    while True:
        try:
            x = (yield)  # Capture the value that's sent
            coro.send(x)  # and pass it to the writer
        except StopIteration:
            pass

Or, we could do this.

def writer_wrapper(coro):
    yield from coro

That saves 6 lines of code, make it much much more readable and it just works. Magic!

Sending data to a generator yield from - Part 2 - Exception handling

Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one.

class SpamException(Exception):
    pass

def writer():
    while True:
        try:
            w = (yield)
        except SpamException:
            print('***')
        else:
            print('>> ', w)

What if we don't change writer_wrapper? Does it work? Let's try

# writer_wrapper same as above

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
    if i == 'spam':
        wrap.throw(SpamException)
    else:
        wrap.send(i)

# Expected Result
>>  0
>>  1
>>  2
***
>>  4

# Actual Result
>>  0
>>  1
>>  2
Traceback (most recent call last):
  ... redacted ...
  File ... in writer_wrapper
    x = (yield)
__main__.SpamException

Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer)

def writer_wrapper(coro):
    """Works. Manually catches exceptions and throws them"""
    coro.send(None)  # prime the coro
    while True:
        try:
            try:
                x = (yield)
            except Exception as e:   # This catches the SpamException
                coro.throw(e)
            else:
                coro.send(x)
        except StopIteration:
            pass

This works.

# Result
>>  0
>>  1
>>  2
***
>>  4

But so does this!

def writer_wrapper(coro):
    yield from coro

The yield from transparently handles sending the values or throwing values into the sub-generator.

This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases.

I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.

In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator.

References:

  1. PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
  2. PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

At the moment, this can be done as follows

$ANDROID_HOME/build-tools/28.0.3/aapt dump badging /<path to>/<app name>.apk

In General, it will be:

$ANDROID_HOME/build-tools/<version_of_build_tools>/aapt dump badging /<path to>/<app name>.apk

Animate scroll to ID on page load

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

How to resolve Value cannot be null. Parameter name: source in linq?

Error message clearly says that source parameter is null. Source is the enumerable you are enumerating. In your case it is ListMetadataKor object. And its definitely null at the time you are filtering it second time. Make sure you never assign null to this list. Just check all references to this list in your code and look for assignments.

select2 onchange event only works once

$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});

How to right align widget in horizontal linear layout Android?

For aligning one element at start and one at the end of the LinearLayout, you can wrap it in an RelativeLayout.

 <androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_margin="8dp"
    android:weightSum="2">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="start">
        <com.google.android.material.button.MaterialButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancel"
            android:textColor="@android:color/background_dark"
            android:backgroundTint="@android:color/transparent"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="end">
        <com.google.android.material.button.MaterialButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/background_dark"
            android:backgroundTint="@android:color/transparent"
            android:text="Save"/>
    </RelativeLayout>
</androidx.appcompat.widget.LinearLayoutCompat>

The result of this example is following: Link to the image

Note: You can wrap whatever you want inside and align it.

SQL: How do I SELECT only the rows with a unique value on certain column?

For MySQL:

SELECT contract, activity
FROM table
GROUP BY contract
HAVING COUNT(DISTINCT activity) = 1

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Execute a file with arguments in Python shell

If you set PYTHONINSPECT in the python file you want to execute

[repl.py]

import os
import sys
from time import time 
os.environ['PYTHONINSPECT'] = 'True'
t=time()
argv=sys.argv[1:len(sys.argv)]

there is no need to use execfile, and you can directly run the file with arguments as usual in the shell:

python repl.py one two 3
>>> t
1513989378.880822
>>> argv
['one', 'two', '3']

jQuery Datepicker localization

Datepicker in german (Deutsch):

$.datepicker.regional['de'] = {
    monthNames: ['Januar','Februar','März','April','Mai','Juni',
    'Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
    'Jul','Aug','Sep','Okt','Nov','Dez'],
    dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
    dayNamesShort: ['Son','Mon','Die','Mit','Don','Fre','Sam'],
    dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
    firstDay: 1};
 $.datepicker.setDefaults($.datepicker.regional['de']);

Perform Button click event when user press Enter key in Textbox

Put your form inside an asp.net panel control and set its defaultButton attribute with your button Id. See the code below:

  <asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
             </ContentTemplate>
          </asp:UpdatePanel>
    </asp:Panel>

Hope this will help you...

How do I convert a number to a letter in Java?

for(int i=0;i<ar.length();i++) {
            char ch = ar.charAt(i);
                    System.out.println((char)(ch+16));;
        }

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

How can I generate a random number in a certain range?

private int getRandomNumber(int min,int max) {
    return (new Random()).nextInt((max - min) + 1) + min;
}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

This is object not an array:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

You probably want:

var data = [{
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
}];

Installing PIL with pip

These days, everyone uses Pillow, a friendly PIL fork, over PIL.

Instead of: sudo pip install pil

Do: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

Bash: Echoing a echo command with a variable in bash

echo "echo "we are now going to work with ${ser}" " >> $servfile

Escape all " within quotes with \. Do this with variables like \$servicetest too:

echo "echo \"we are now going to work with \${ser}\" " >> $servfile    
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile

Reversing a string in C

bool reverse_string(char* str) {
    if(str == NULL){
        return false;
    }
    if(strlen(str) < 2){
        return false;
    }
    
    char* first = str;
    char* last = str + strlen(str) - 1; // Minus 1 accounts for Index offset
    char temp;

    do{
        temp = *first;
        *first = *last;
        *last = temp;
    }
    while (++first < --last); // Update Pointer Addresses and check for equality

    return true;
}

This solution is based on GManNickG's post with a few modifications. The initial logical statement may be dangerous if !str is not evaluated before the strlen operation (For a NULL ptr). This wasn't the case with my compiler. I thought I would add this code because its a nice example of a do-while loop.

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Preventing HTML and Script injections in Javascript

You can encode the < and > to their HTML equivelant.

html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");

How to display HTML tags as plain text

Why use getters and setters/accessors?

Lots of people talk about the advantages of getters and setters but I want to play devil's advocate. Right now I'm debugging a very large program where the programmers decided to make everything getters and setters. That might seem nice, but its a reverse-engineering nightmare.

Say you're looking through hundreds of lines of code and you come across this:

person.name = "Joe";

It's a beautifully simply piece of code until you realize its a setter. Now, you follow that setter and find that it also sets person.firstName, person.lastName, person.isHuman, person.hasReallyCommonFirstName, and calls person.update(), which sends a query out to the database, etc. Oh, that's where your memory leak was occurring.

Understanding a local piece of code at first glance is an important property of good readability that getters and setters tend to break. That is why I try to avoid them when I can, and minimize what they do when I use them.

"Fatal error: Cannot redeclare <function>"

I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.

Declare your function as a lambda expression (I haven't seen this solution mentioned):

$generate_salt = function()
{
    ...
};

And use thusly:

$salt = $generate_salt();

Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.

How do I push amended commit to the remote Git repository?

I had to fix this problem with pulling from the remote repo and deal with the merge conflicts that arose, commit and then push. But I feel like there is a better way.

How to Install gcc 5.3 with yum on CentOS 7.2?

Update: Installing latest version of gcc 9: (gcc 9.3.0) - released March 12, 2020:

Same method can be applied to gcc 10 (gcc 10.1.0) - released May 7, 2020

Download file: gcc-9.3.0.tar.gz or gcc-10.1.0.tar.gz

Compile and install:

//required libraries: (some may already have been installed)
dnf install libmpc-devel mpfr-devel gmp-devel

//if dnf install libmpc-devel is not working try:
dnf --enablerepo=PowerTools install libmpc-devel

//install zlib
dnf install zlib-devel*

./configure --with-system-zlib --disable-multilib --enable-languages=c,c++

make -j 8 <== this may take around an hour or more to finish
              (depending on your cpu speed)

make install

Tested under CentOS 7.8.2003 for gcc 9.3 and gcc 10.1

Tested under CentOS 8.1.1911 for gcc 10.1 (may take more time to compile)

Results: gcc/g++ 9.3.0/10.1.0

enter image description here enter image description here

Installing gcc 7.4 (gcc 7.4.0) - released December 6, 2018:

Download file: https://ftp.gnu.org/gnu/gcc/gcc-7.4.0/gcc-7.4.0.tar.gz

Compile and install:

//required libraries:
yum install libmpc-devel mpfr-devel gmp-devel

./configure --with-system-zlib --disable-multilib --enable-languages=c,c++

make -j 8 <== this may take around 50 minutes or less to finish with 8 threads
              (depending on your cpu speed)


make install

Result:

enter image description here

Notes:

1. This Stack Overflow answer will help to see how to verify the downloaded source file.

2. Use the option --prefix to install gcc to another directory other than the default one. The toplevel installation directory defaults to /usr/local. Read about gcc installation options

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

React - Display loading screen while DOM is rendering?

Edit your index.html file location in the public folder. Copy your image to same location as index.html in public folder. And then replace the part of the contents of index.html containing <div id="root"> </div> tags to the below given html code.

<div id="root">  <img src="logo-dark300w.png" alt="Spideren" style="vertical-align: middle; position: absolute;
   top: 50%;
   left: 50%;
   margin-top: -100px; /* Half the height */
   margin-left: -250px; /* Half the width */" />  </div>

Logo will now appear in the middle of the page during the loading process. And will then be replaced after a few seconds by React.

Why is my method undefined for the type object?

It should be like that

public static void main(String[] args) {
        EchoServer0 e = new EchoServer0();
        // TODO Auto-generated method stub
        e.listen();
}

Your variable of type Object truly doesn't have such a method, but the type EchoServer0 you define above certainly has.

Appending to list in Python dictionary

list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date)

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

This will create a new list object, if the key is not found in the dictionary.

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

Node.js request CERT_HAS_EXPIRED

Here is a more concise way to achieve the "less insecure" method proposed by CoolAJ86

request({
  url: url,
  agentOptions: {
    rejectUnauthorized: false
  }
}, function (err, resp, body) {
  // ...
});

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

Side-by-side list items as icons within a div (css)

This can be a pure CSS solution. Given:

<ul class="tileMe">
    <li>item 1<li>
    <li>item 2<li>
    <li>item 3<li>
</ul>

The CSS would be:

.tileMe li {
    display: inline;
    float: left;
}

Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:

<li><a class="tile" href="home">item 1</a></li>

and add the following CSS:

.tile a {
    display: block;
    padding: 10px;
    border: 1px solid red;
    margin-right: 5px;
}

The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.

How to handle anchor hash linking in AngularJS

$anchorScroll works for this, but there's a much better way to use it in more recent versions of Angular.

Now, $anchorScroll accepts the hash as an optional argument, so you don't have to change $location.hash at all. (documentation)

This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set $location.hash(id), before $anchorScroll could do its magic.

Here is how to use it... first, in the directive or controller:

$scope.scrollTo = function (id) {
  $anchorScroll(id);  
}

and then in the view:

<a href="" ng-click="scrollTo(id)">Text</a>

Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):

.run(function ($anchorScroll) {
   //this will make anchorScroll scroll to the div minus 50px
   $anchorScroll.yOffset = 50;
});

Adding the "Clear" Button to an iPhone UITextField

Objective C :

self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

Swift :

txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;

Sending mail attachment using Java

For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.

If you want both attachment and text try this based on the accepted answer :

    Properties props = new java.util.Properties();
    props.put("mail.smtp.host", "yourHost");
    props.put("mail.smtp.port", "yourHostPort");
    props.put("mail.smtp.auth", "true");             
    props.put("mail.smtp.starttls.enable", "true");


    // Session session = Session.getDefaultInstance(props, null);
    Session session = Session.getInstance(props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("user", "password");
                }
              });


    Message msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        msg.setSubject("your subject");

        Multipart multipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText("your text");

        MimeBodyPart attachmentBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"

        multipart.addBodyPart(textBodyPart);  // add the text part
        multipart.addBodyPart(attachmentBodyPart); // add the attachement part

        msg.setContent(multipart);


        Transport.send(msg);
    } catch (MessagingException e) {
        LOGGER.log(Level.SEVERE,"Error while sending email",e);
    }

Update :

If you want to send a mail as an html content formated you have to do

    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setContent(content, "text/html");

So basically setText is for raw text and will be well display on every server email including gmail, setContent is more for an html template and if you content is formatted as html it will maybe also works in gmail

What is the best way to use a HashMap in C++?

For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:

  1. In your class you need to define an equality operator overload ==. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/

  2. Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/

namespace std {

  template<>
  struct hash<my_type> {
    size_t operator()(const my_type& k) {
      // Do your hash function here
      ...
    }
  };

}
  1. So then to implement a hashtable using your new hash function, you just have to create a std::map or std::unordered_map just like you would normally do and use my_type as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.
#include <unordered_map>

int main() {
  std::unordered_map<my_type, other_type> my_map;
}

How to convert a Date to a formatted string in VB.net?

you can do it using the format function, here is a sample:

Format(mydate, "yyyy-MM-dd HH:mm:ss")

File Upload to HTTP server in iphone programming

This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"]; 
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

How to highlight text using javascript

Simply pass your word into the following function:

function highlight_words(word) {
    const page = document.body.innerHTML;
    document.body.innerHTML = page.replace(new RegExp(word, "gi"), (match) => `<mark>${match}</mark>`);
}

Usage:

highlight_words("hello")

This will highlight all instances of the word on the page.

Appropriate datatype for holding percent values?

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

Example Scenarios

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

Example:

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

Further Reading:

multiple prints on the same line in Python

print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

PHP - concatenate or directly insert variables in string

I know this is an old question, but I think someone has to mention all pros & cons:

Better Syntax: That's personal preference.

Performance: No difference. As many mentioned, double-quote might be faster if using unrealistically many variables.

Better Usage: Single quote (mostly). As @Khez said, with single quote you can concatenate anything, even function calls and variable modification, like so: echo 'hi ' . trim($name) . ($i + 1);. The only thing double-quote can do that single-quote cannot do is usage of \n, \r, \t and alike.

Readability: No difference (may personal preference apply).

Writability/Re-Writability/Debugging: In 1-line statements there is no difference, but when dealing with multiple lines, it's easier to comment/uncomment lines while debugging or writing. For example:

$q = 'SELECT ' .
     't1.col1 ' .
     ',t2.col2 ' .
   //',t3.col3 ' .
     'FROM tbl1 AS t1 ' .
     'LEFT JOIN tbl2 AS t2 ON t2.col2 = t1.col1 ' .
   //'LEFT JOIN tbl3 AS t3 ON t3.col3 = t2.col2 ' .
     'WHERE t1.col1 = ' . $x . ' ' .
     '  AND t2.col2 = ' . $y . ' ' .
   //'  AND t3.col3 = ' . $z . ' ' .
     'ORDER BY t1.col1 ASC ' .
     'LIMIT 10';

Less Escaping: Single-quote. For single quote you need to escape 2 characters only (' and \). For double quote you need to escape 2 characters (", \) and 3 more if required ($, { and }).

Less Changes: Single quote. For example if you have the following code:

echo 'Number ' . $i . '!';

And you need to increment 1 to $i, so it becomes likes:

echo 'Number ' . ($i + 1) . '!';

But for double quote, you will need to change this:

echo "Number $i!";

to this:

echo "Number " . ($i + 1) . "!";

Conclusion: Use what you prefer.

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Image Greyscale with CSS & re-color on mouse-over?

There are numerous methods of accomplishing this, which I'll detail with a few examples below.

Pure CSS (using only one colored image)

img.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}

img.grayscale:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
}

_x000D_
_x000D_
img.grayscale {_x000D_
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
  /* Firefox 3.5+, IE10 */_x000D_
  filter: gray;_x000D_
  /* IE6-9 */_x000D_
  -webkit-filter: grayscale(100%);_x000D_
  /* Chrome 19+ & Safari 6+ */_x000D_
  -webkit-transition: all .6s ease;_x000D_
  /* Fade to color for Chrome and Safari */_x000D_
  -webkit-backface-visibility: hidden;_x000D_
  /* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
  filter: none;_x000D_
  -webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
  background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
  transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
  <defs>_x000D_
     <filter id="filtersPicture">_x000D_
       <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
       <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
   </svg>
_x000D_
_x000D_
_x000D_

You can find an article related to this technique here.

Pure CSS (using a grayscale and colored images)

This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover psuedoselector, you can update the background of your element to toggle between the two:

#yourimage { 
    background: url(../grayscale-image.png);
}
#yourImage:hover { 
    background: url(../color-image.png};
}

_x000D_
_x000D_
#google {_x000D_
  background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
  height: 95px;_x000D_
  width: 275px;_x000D_
  display: block;_x000D_
  /* Optional for a gradual animation effect */_x000D_
  transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
  background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
_x000D_
_x000D_

This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover() function in the same manner.

Consider a Third-Party Library

The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.

what happens when you type in a URL in browser

Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server's IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it's gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Using Pip to install packages to Anaconda Environment

Well I tried all the above methods. None worked for me. The following worked for me:

  1. Activate your environment
  2. Download the .whl package manually from https://pypi.org/simple//
  3. Navigate to the folder where you have downloaded the .whl from the command line with your environment activated
  4. perform: pip install package_name_whatever.whl

Where can I find the TypeScript version installed in Visual Studio?

You can run it in NuGet Package Manager Console in Visual Studio 2013.

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

How to pass arguments and redirect stdin from a file to program run in gdb?

Wouldn't it be nice to just type debug in front of any command to be able to debug it with gdb on shell level?

Below it this function. It even works with following:

"$program" "$@" < <(in) 1> >(out) 2> >(two) 3> >(three)

This is a call where you cannot control anything, everything is variable, can contain spaces, linefeeds and shell metacharacters. In this example, in, out, two, and three are arbitrary other commands which consume or produce data which must not be harmed.

Following bash function invokes gdb nearly cleanly in such an environment [Gist]:

debug()
{
  1000<&0 1001>&1 1002>&2 \
  0</dev/tty 1>/dev/tty 2>&0 \
  /usr/bin/gdb -q -nx -nw \
  -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" exec' \
  -ex r \
  --args "$@";
}

Example on how to apply this: Just type debug in front:

Before:

p=($'\n' $'I\'am\'evil' "  yay  ")
"b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

After:

p=($'\n' $'I\'am\'evil' "  yay  ")
debug "b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

That's it. Now it's an absolute no-brainer to debug with gdb. Except for a few details or more:

  • gdb does not quit automatically and hence keeps the IO redirection open until you exit gdb. But I call this a feature.

  • You cannot easily pass argv0 to the program like with exec -a arg0 command args. Following should do this trick: After exec-wrapper change "exec to "exec -a \"\${DEBUG_ARG0:-\$1}\".

  • There are FDs above 1000 open, which are normally closed. If this is a problem, change 0<&1000 1>&1001 2>&1002 to read 0<&1000 1>&1001 2>&1002 1000<&- 1001>&- 1002>&-

  • You cannot run two debuggers in parallel. There also might be issues, if some other command consumes /dev/tty (or STDIN). To fix that, replace /dev/tty with "${DEBUGTTY:-/dev/tty}". In some other TTY type tty; sleep inf and then use the printed TTY (i. E. /dev/pts/60) for debugging, as in DEBUGTTY=/dev/pts/60 debug command arg... That's the Power of Shell, get used to it!

Function explained:

  • 1000<&0 1001>&1 1002>&2 moves away the first 3 FDs
    • This assumes, that FDs 1000, 1001 and 1002 are free
  • 0</dev/tty 1>/dev/tty 2>&0 restores the first 3 FDs to point to your current TTY. So you can control gdb.
  • /usr/bin/gdb -q -nx -nw runs gdb invokes gdb on shell
  • -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" creates a startup wrapper, which restores the first 3 FDs which were saved to 1000 and above
  • -ex r starts the program using the exec-wrapper
  • --args "$@" passes the arguments as given

Wasn't that easy?

com.sun.jdi.InvocationException occurred invoking method

I have received com.sun.jdi.InvocationException occurred invoking method when I lazy loaded entity field which used secondary database config (Spring Boot with 2 database configs - lazy loading with second config does not work). Temporary solution was to add FetchType.EAGER.

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

How to give color to each class in scatter plot in R?

If you have the classes separated in a data frame or a matrix, then you can use matplot. For example, if we have

dat<-as.data.frame(cbind(c(1,2,5,7),c(2.1,4.2,-0.5,1),c(9,3,6,2.718)))

plot.new()
plot.window(c(0,nrow(dat)),range(dat))
matplot(dat,col=c("red","blue","yellow"),pch=20)

Then you'll get a scatterplot where the first column of dat is plotted in red, the second in blue, and the third in yellow. Of course, if you want separate x and y values for your color classes, then you can have datx and daty, etc.

An alternate approach would be to tack on an extra column specifying what color you want (or keeping an extra vector of colors, filling it iteratively with a for loop and some if branches). For example, this will get you the same plot:

dat<-as.data.frame(
    cbind(c(1,2,5,7,2.1,4.2,-0.5,1,9,3,6,2.718)
    ,c(rep("red",4),rep("blue",4),rep("yellow",4))))

dat[,1]=as.numeric(dat[,1]) #This is necessary because
                            #the second column consisting of strings confuses R
                            #into thinking that the first column must consist of strings, too
plot(dat[,1],pch=20,col=dat[,2])