Programs & Examples On #User input

User Input is data that the user inputs into the program. It generally takes the form of a String, but may also be an integer, floating-point number, etc.

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

Asking the user for input until they give a valid response

Building upon Daniel Q's and Patrick Artner's excellent suggestions, here is an even more generalized solution.

# Assuming Python3
import sys

class ValidationError(ValueError):  # thanks Patrick Artner
    pass

def validate_input(prompt, cast=str, cond=(lambda x: True), onerror=None):
    if onerror==None: onerror = {}
    while True:
        try:
            data = cast(input(prompt))
            if not cond(data): raise ValidationError
            return data
        except tuple(onerror.keys()) as e:  # thanks Daniel Q
            print(onerror[type(e)], file=sys.stderr)

I opted for explicit if and raise statements instead of an assert, because assertion checking may be turned off, whereas validation should always be on to provide robustness.

This may be used to get different kinds of input, with different validation conditions. For example:

# No validation, equivalent to simple input:
anystr = validate_input("Enter any string: ")

# Get a string containing only letters:
letters = validate_input("Enter letters: ",
    cond=str.isalpha,
    onerror={ValidationError: "Only letters, please!"})

# Get a float in [0, 100]:
percentage = validate_input("Percentage? ",
    cast=float, cond=lambda x: 0.0<=x<=100.0,
    onerror={ValidationError: "Must be between 0 and 100!",
             ValueError: "Not a number!"})

Or, to answer the original question:

age = validate_input("Please enter your age: ",
        cast=int, cond=lambda a:0<=a<150,
        onerror={ValidationError: "Enter a plausible age, please!",
                 ValueError: "Enter an integer, please!"})
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

How to use View.OnTouchListener instead of onClick

OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:

myView.setOnTouchListener(new View.OnTouchListener()
{
    // Implementation;
});

Spring MVC: How to perform validation?

There are two ways to validate user input: annotations and by inheriting Spring's Validator class. For simple cases, the annotations are nice. If you need complex validations (like cross-field validation, eg. "verify email address" field), or if your model is validated in multiple places in your application with different rules, or if you don't have the ability to modify your model object by placing annotations on it, Spring's inheritance-based Validator is the way to go. I'll show examples of both.

The actual validation part is the same regardless of which type of validation you're using:

RequestMapping(value="fooPage", method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("foo") Foo foo, BindingResult result, ModelMap m) {
    if(result.hasErrors()) {
        return "fooPage";
    }
    ...
    return "successPage";
}

If you are using annotations, your Foo class might look like:

public class Foo {

    @NotNull
    @Size(min = 1, max = 20)
    private String name;

    @NotNull
    @Min(1)
    @Max(110)
    private Integer age;

    // getters, setters
}

Annotations above are javax.validation.constraints annotations. You can also use Hibernate's org.hibernate.validator.constraints, but it doesn't look like you are using Hibernate.

Alternatively, if you implement Spring's Validator, you would create a class as follows:

public class FooValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Foo.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        Foo foo = (Foo) target;

        if(foo.getName() == null) {
            errors.rejectValue("name", "name[emptyMessage]");
        }
        else if(foo.getName().length() < 1 || foo.getName().length() > 20){
            errors.rejectValue("name", "name[invalidLength]");
        }

        if(foo.getAge() == null) {
            errors.rejectValue("age", "age[emptyMessage]");
        }
        else if(foo.getAge() < 1 || foo.getAge() > 110){
            errors.rejectValue("age", "age[invalidAge]");
        }
    }
}

If using the above validator, you also have to bind the validator to the Spring controller (not necessary if using annotations):

@InitBinder("foo")
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new FooValidator());
}

Also see Spring docs.

Hope that helps.

Javascript - User input through HTML input tag to set a Javascript variable?

When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

  • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
  • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.

JavaScript: Check if mouse button down?

If you're working within a complex page with existing mouse event handlers, I'd recommend handling the event on capture (instead of bubble). To do this, just set the 3rd parameter of addEventListener to true.

Additionally, you may want to check for event.which to ensure you're handling actual user interaction and not mouse events, e.g. elem.dispatchEvent(new Event('mousedown')).

var isMouseDown = false;

document.addEventListener('mousedown', function(event) { 
    if ( event.which ) isMouseDown = true;
}, true);

document.addEventListener('mouseup', function(event) { 
    if ( event.which ) isMouseDown = false;
}, true);

Add the handler to document (or window) instead of document.body is important b/c it ensures that mouseup events outside of the window are still recorded.

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

Password masking console application

 string pass = "";
 Console.WriteLine("Enter your password: ");
 ConsoleKeyInfo key;

 do {
  key = Console.ReadKey(true);

  if (key.Key != ConsoleKey.Backspace) {
   pass += key.KeyChar;
   Console.Write("*");
  } else {
   Console.Write("\b \b");
   char[] pas = pass.ToCharArray();
   string temp = "";
   for (int i = 0; i < pass.Length - 1; i++) {
    temp += pas[i];
   }
   pass = temp;
  }
 }
 // Stops Receving Keys Once Enter is Pressed
 while (key.Key != ConsoleKey.Enter);

 Console.WriteLine();
 Console.WriteLine("The Password You entered is : " + pass);

How can I sanitize user input with PHP?

It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called magic-quotes, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).

What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.

Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.

A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.

Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, json_encode() that will correctly format every bit of data.

And so on and so forth ...

The only case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You will need to repeat your call to strtol inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...); instead of while, you don't get a the same sort of repeat things twice behaviour.

You should also format your code so that it's possible to see where the code is inside a loop and not.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

use a temporary scan.nextLine(); this will consume the \n character

How to get input from user at runtime

you can try this too And it will work:

DECLARE
  a NUMBER;
  b NUMBER;
BEGIN
  a :=: a; --this will take input from user
  b :=: b;
  DBMS_OUTPUT.PUT_LINE('a = '|| a);
  DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;

How do you implement a good profanity filter?

Also late in the game, but doing some researches and stumbled across here. As others have mentioned, it's just almost close to impossible if it was automated, but if your design/requirement can involve in some cases (but not all the time) human interactions to review whether it is profane or not, you may consider ML. https://docs.microsoft.com/en-us/azure/cognitive-services/content-moderator/text-moderation-api#profanity is my current choice right now for multiple reasons:

  • Supports many localization
  • They keep updating the database, so I don't have to keep up with latest slangs or languages (maintenance issue)
  • When there is a high probability (I.e. 90% or more) you can just deny it pragmatically
  • You can observe for category which causes a flag that may or may not be profanity, and can have somebody review it to teach that it is or isn't profane.

For my need, it was/is based on public-friendly commercial service (OK, videogames) which other users may/will see the username, but the design requires that it has to go through profanity filter to reject offensive username. The sad part about this is the classic "clbuttic" issue will most likely occur since usernames are usually single word (up to N characters) of sometimes multiple words concatenated... Again, Microsoft's cognitive service will not flag "Assist" as Text.HasProfanity=true but may flag one of the categories probability to be high.

As the OP inquires, what about "a$$", here's a result when I passed it through the filter:enter image description here, as you can see, it has determined it's not profane, but it has high probability that it is, so flags as recommendations of reviewing (human interactions).

When probability is high, I can either return back "I'm sorry, that name is already taken" (even if it isn't) so that it is less offensive to anti-censorship persons or something, if we don't want to integrate human review, or return "Your username have been notified to the live operation department, you may wait for your username to be reviewed and approved or chose another username". Or whatever...

By the way, the cost/price for this service is quite low for my purpose (how often does the username gets changed?), but again, for OP maybe the design demands more intensive queries and may not be ideal to pay/subscribe for ML-services, or cannot have human-review/interactions. It all depends on the design... But if design does fit the bill, perhaps this can be OP's solution.

If interested, I can list the cons in the comment in the future.

How to show "Done" button on iPhone number pad

I found @user1258240's answer to be pretty concise given this is not as simple as setting a returnKeyType property.

Just wanted to contribute my own "re-usable" approach to this:

func SetDoneToolbar(field:UITextField) {
    let doneToolbar:UIToolbar = UIToolbar()

    doneToolbar.items=[
        UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil),
        UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.dismissKeyboard))
    ]

    doneToolbar.sizeToFit()
    field.inputAccessoryView = doneToolbar
}

override func viewDidLoad() {
    super.viewDidLoad()

    SetDoneToolbar(field: UITextField_1)
    SetDoneToolbar(field: UITextField_2)
    SetDoneToolbar(field: UITextField_3)
    SetDoneToolbar(field: UITextField_N)
}

Converting String Array to an Integer Array

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

How to save user input into a variable in html and js

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

See http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}

HTML not loading CSS file

With HTML5 all you need is the rel, not even the type.

<link href="custom.css" rel="stylesheet"></link>

Fastest JavaScript summation

For your specific case, just use the reduce method of Arrays:

var sumArray = function() {
    // Use one adding function rather than create a new one each
    // time sumArray is called
    function add(a, b) {
        return a + b;
    }

    return function(arr) {
        return arr.reduce(add);
    };
}();

alert( sumArray([2, 3, 4]) );

'pip' is not recognized as an internal or external command

If you are working with Python, e.g. PyCharm, you should install the library to the Python library path like this:

pip install --target=C:\Users\<...>\lib <Library-Name>

real e.g.

pip install --target=C:\Users\devel\AppData\Local\Programs\Python\Python36\Lib requests <br>

PS: If you want to check if it's installed,

<Library-Name> --version

will not work correctly.

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

The foo.bar reference should not contain the braces:

<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>

Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.

See also Understanding Angular Templates.

How to Load Ajax in Wordpress

I'm not allowed to comment, so regarding Shane's answer, keep in mind that

wp_localize_scripts()

must be hooked to wp or admin enqueue scripts. So a good example would be as follows:

function local() {

    wp_localize_script( 'js-file-handle', 'ajax', array(
        'url' => admin_url( 'admin-ajax.php' )
    ) );

}

add_action('admin_enqueue_scripts', 'local');
add_action('wp_enqueue_scripts', 'local');`

how to get the one entry from hashmap without iterating

Get values, convert it to an array, get array's first element:

map.values().toArray()[0]

W.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...

Update: The page states that the tight_layout() function is the easiest way to go, which attempts to automatically correct spacing.

Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

Reading the selected value from asp:RadioButtonList using jQuery

Why so complex?

$('#id:checked').val();

Will work just fine!

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I would first try resetting all Visual Studio settings (Tools > Import and Export Settings > Reset all settings), then go to the Resharper > Options > Keyboard & Menus and re-apply the keyboard shortcut scheme.

I had to do something similar once.

The smallest difference between 2 Angles

A simple method, which I use in C++ is:

double deltaOrientation = angle1 - angle2;
double delta =  remainder(deltaOrientation, 2*M_PI);

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

How to find a value in an array of objects in JavaScript?

If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just 'name' in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

java Arrays.sort 2d array

Java 8 is now very common nowadays.

Arrays.sort(myArr,(double[] a,double[] b)->{
                //here multiple lines of code can be placed
                return a[0]-b[0]; 
            });

Detect if PHP session exists

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();

CSS force image resize and keep aspect ratio

Remove the "height" property.

<img src="big_image.jpg" width="900" alt=""/>

By specifying both you are changing the aspect ratio of the image. Just setting one will resize but preserve the aspect ratio.

Optionally, to restrict oversizings:

<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

WPF - add static items to a combo box

Like this:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

How to check if a String contains another String in a case insensitive manner in Java?

There is a simple concise way, using regex flag (case insensitive {i}):

 String s1 = "hello abc efg";
 String s2 = "ABC";
 s1.matches(".*(?i)"+s2+".*");

/*
 * .*  denotes every character except line break
 * (?i) denotes case insensitivity flag enabled for s2 (String)
 * */

How to deep copy a list?

just a recursive deep copy function.

def deepcopy(A):
    rt = []
    for elem in A:
        if isinstance(elem,list):
            rt.append(deepcopy(elem))
        else:
            rt.append(elem)
    return rt

Edit: As Cfreak mentioned, this is already implemented in copy module.

How to set up subdomains on IIS 7

If your computer can't find the IP address associated with SUBDOMAIN1.example.COM, it will not find the site.

You need to either change your hosts file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).

Address already in use: JVM_Bind

on windows open a cmd.exe window with administrator permissions and use netstat -a -b -o you will get the id of the proccess that holds your port and be able to kill it using task manager.

Get all dates between two dates in SQL Server

This can be considered as bit tricky way as in my situation, I can't use a CTE table, so decided to join with sys.all_objects and then created row numbers and added that to start date till it reached the end date.

See the code below where I generated all dates in Jul 2018. Replace hard coded dates with your own variables (tested in SQL Server 2016):

select top (datediff(dd, '2018-06-30', '2018-07-31')) ROW_NUMBER() 
over(order by a.name) as SiNo, 
Dateadd(dd, ROW_NUMBER() over(order by a.name) , '2018-06-30') as Dt from sys.all_objects a

How to get jQuery dropdown value onchange event

Try like this

 $("#drop").change(function () {
        var end = this.value;
        var firstDropVal = $('#pick').val();
    });

How to convert SQL Query result to PANDAS Data Structure?

Here's the shortest code that will do the job:

from pandas import DataFrame
df = DataFrame(resoverall.fetchall())
df.columns = resoverall.keys()

You can go fancier and parse the types as in Paul's answer.

Datetime format Issue: String was not recognized as a valid DateTime

You may use this type format (get formatted data from sql server)


FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')


CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

Convert unix time to readable date in pandas dataframe

Assuming we imported pandas as pd and df is our dataframe

pd.to_datetime(df['date'], unit='s')

works for me.

how to make password textbox value visible when hover an icon

Complete example below. I just love the copy/paste :)

HTML

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
              <div class="panel-body">
                  <form class="form-horizontal" method="" action="">

                     <div class="form-group">
                        <label class="col-md-4 control-label">Email</label>
                           <div class="col-md-6">
                               <input type="email" class="form-control" name="email" value="">
                           </div>
                     </div>
                     <div class="form-group">
                       <label class="col-md-4 control-label">Password</label>
                          <div class="col-md-6">
                              <input id="password-field" type="password" class="form-control" name="password" value="secret">
                              <span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
                          </div>
                     </div>
                 </form>
              </div>
           </div>
      </div>
  </div>

CSS

.field-icon {
  float: right;
  margin-right: 8px;
  margin-top: -23px;
  position: relative;
  z-index: 2;
  cursor:pointer;
}

.container{
  padding-top:50px;
  margin: auto;
}

JS

$(".toggle-password").click(function() {
   $(this).toggleClass("fa-eye fa-eye-slash");
   var input = $($(this).attr("toggle"));
   if (input.attr("type") == "password") {
     input.attr("type", "text");
   } else {
     input.attr("type", "password");
   }
});

Try it here: https://codepen.io/anon/pen/ZoMQZP

Dynamic creation of table with DOM

<title>Registration Form</title>
<script>
    var table;

    function check() {
        debugger;
        var name = document.myForm.name.value;
        if (name == "" || name == null) {
            document.getElementById("span1").innerHTML = "Please enter the Name";
            document.myform.name.focus();
            document.getElementById("name").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span1").innerHTML = "";
            document.getElementById("name").style.border = "2px solid green";
        }

        var age = document.myForm.age.value;
        var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;

        if (age == "" || age == null) {
            document.getElementById("span2").innerHTML = "Please provide Age";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else if (!ageFormat.test(age)) {
            document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span2").innerHTML = "";
            document.getElementById("age").style.border = "2px solid green";
        }

        var password = document.myForm.password.value;
        if (document.myForm.password.length < 6) {
            alert("Error: Password must contain at least six characters!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[0-9]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one number (0-9)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[a-z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one lowercase letter (a-z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[A-Z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one uppercase letter (A-Z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[$&+,:;=?@#|'<>.^*()%!-]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one special character!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span3").innerHTML = "";
            document.getElementById("password").style.border = "2px solid green";

        }

        if (document.getElementById("data") == null)
            createTable();
        else {
            appendRow();
        }
        return true;
    }






    function createTable() {

        var myTableDiv = document.getElementById("myTable");  //indiv
        table = document.createElement("TABLE");   //TABLE??
        table.setAttribute("id", "data");
        table.border = '1';
        myTableDiv.appendChild(table);  //appendChild() insert it in the document (table --> myTableDiv)
        debugger;

        var header = table.createTHead();

        var th0 = table.tHead.appendChild(document.createElement("th"));
        th0.innerHTML = "Name";
        var th1 = table.tHead.appendChild(document.createElement("th"));
        th1.innerHTML = "Age";


        appendRow();

    }

    function appendRow() {
        var name = document.myForm.name.value;
        var age = document.myForm.age.value;


        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        row.insertCell(0).innerHTML = name;
        row.insertCell(1).innerHTML = age;



        clearForm();


    }


    function clearForm() {
        debugger;

        document.myForm.name.value = "";
        document.myForm.password.value = "";
        document.myForm.age.value = "";



    }
    function restrictCharacters(evt) {

        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
            return true;
        }
        else {
            return false;
        }
    }

</script>



<div>
    <form name="myForm">

        <table id="tableid">

            <tr>
                <th>Name</th>
                <td>
                    <input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
                <td><span id="span1"></span></td>
            </tr>

            <tr>
                <th>Age</th>

                <td>
                    <input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
                        name="age" id="age" /></td>
                <td><span id="span2"></span></td>
            </tr>

            <tr>
                <th>Password</th>
                <td>
                    <input type="password" name="password" id="password" placeholder="Password" /></td>
                <td><span id="span3"></span></td>
            </tr>


            <tr>
                <td></td>
                <td>
                    <input type="button" value="Submit" onclick="check();" /></td>
                <td>
                    <input type="reset" name="Reset" /></td>
            </tr>

        </table>
    </form>

    <div id="myTable">
    </div>

</div>

How to download a Nuget package without nuget.exe or Visual Studio extension?

Although building the URL or using tools is still possible, it is not needed anymore.

https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.

(at the bottom of the right column).


Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)

Example of EntityFramework's detail page

how to convert 2d list to 2d numpy array?

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

How to read one single line of csv data in Python?

The simple way to get any row in csv file

import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
    csvFileArray.append(row)
print(csvFileArray[0])

What's the difference between event.stopPropagation and event.preventDefault?

Event.preventDefault- stops browser default behaviour. Now comes what is browser default behaviour. Assume you have a anchor tag and it has got a href attribute and this anchor tag is nested inside a div tag which has got a click event. Default behaviour of anchor tag is when clicked on the anchor tag it should navigate, but what event.preventDefault does is it stops the navigation in this case. But it never stops the bubbling of event or escalation of event i.e

<div class="container">
 <a href="#" class="element">Click Me!</a>
</div>

$('.container').on('click', function(e) {
 console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  console.log('element was clicked');
});

The result will be

"element was clicked"

"container was clicked"

Now event.StopPropation it stops bubbling of event or escalation of event. Now with above example

$('.container').on('click', function(e) {
  console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  e.stopPropagation(); // Now the event won't bubble up
 console.log('element was clicked');
});

Result will be

"element was clicked"

For more info refer this link https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

Hexadecimal string to byte array in C

By some modification form user411313's code, following works for me:

#include <stdio.h>
#include <stdint.h> 
#include <string.h>

int main ()
{
    char *hexstring = "deadbeef10203040b00b1e50";
    int i;
    unsigned int bytearray[12];
    uint8_t str_len = strlen(hexstring);

    for (i = 0; i < (str_len / 2); i++) {
        sscanf(hexstring + 2*i, "%02x", &bytearray[i]);
        printf("bytearray %d: %02x\n", i, bytearray[i]);
    }

    return 0;
}

Border around specific rows in a table?

Group rows together using the <tbody> tag and then apply style.

<table>
  <tr><td>No Style here</td></tr>
  <tbody class="red-outline">
    <tr><td>Style me</td></tr>
    <tr><td>And me</td></tr>
  </tbody>
  <tr><td>No Style here</td></tr>
</table>  

And the css in style.css

.red-outline {
  outline: 1px solid red;
}

Make $JAVA_HOME easily changable in Ubuntu

You need to put variable definition in the ~/.bashrc file.

From bash man page:

When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.

Google maps Places API V3 autocomplete - select first option on enter

None of these answers seemed to work for me. They'd get the general location but wouldn't actually pan to the actual place I searched for. Within the .pac-item you can actually get just the address (name of place excluded) by selecting $('.pac-item:first').children()[2].textContent

So here is my solution:

$("#search_field").on("keyup", function(e) {
    if(e.keyCode == 13) {
        searchPlaces();
    }
});

function searchPlaces() {
    var $firstResult = $('.pac-item:first').children();
    var placeName = $firstResult[1].textContent;
    var placeAddress = $firstResult[2].textContent;

    $("#search_field").val(placeName + ", " + placeAddress);

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({"address":placeAddress }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat(),
                lng = results[0].geometry.location.lng(),
                placeName = results[0].address_components[0].long_name,
                latlng = new google.maps.LatLng(lat, lng);

            map.panTo(latlng);
        }
    });
}

I know this question was already answered but figured I'd throw in my 2 cents just in case anyone else was having the same problem as me.

How to get a random value from dictionary?

Since this is homework:

Check out random.sample() which will select and return a random element from an list. You can get a list of dictionary keys with dict.keys() and a list of dictionary values with dict.values().

Finding all positions of substring in a larger string in C#

It could be done in efficient time complexity using KMP algorithm in O(N + M) where N is the length of text and M is the length of the pattern.

This is the implementation and usage:

static class StringExtensions
{
    public static IEnumerable<int> AllIndicesOf(this string text, string pattern)
    {
        if (string.IsNullOrEmpty(pattern))
        {
            throw new ArgumentNullException(nameof(pattern));
        }
        return Kmp(text, pattern);
    }

    private static IEnumerable<int> Kmp(string text, string pattern)
    {
        int M = pattern.Length;
        int N = text.Length;

        int[] lps = LongestPrefixSuffix(pattern);
        int i = 0, j = 0; 

        while (i < N)
        {
            if (pattern[j] == text[i])
            {
                j++;
                i++;
            }
            if (j == M)
            {
                yield return i - j;
                j = lps[j - 1];
            }

            else if (i < N && pattern[j] != text[i])
            {
                if (j != 0)
                {
                    j = lps[j - 1];
                }
                else
                {
                    i++;
                }
            }
        }
    }

    private static int[] LongestPrefixSuffix(string pattern)
    {
        int[] lps = new int[pattern.Length];
        int length = 0;
        int i = 1;

        while (i < pattern.Length)
        {
            if (pattern[i] == pattern[length])
            {
                length++;
                lps[i] = length;
                i++;
            }
            else
            {
                if (length != 0)
                {
                    length = lps[length - 1];
                }
                else
                {
                    lps[i] = length;
                    i++;
                }
            }
        }
        return lps;
    }

and this is an example of how to use it:

static void Main(string[] args)
    {
        string text = "this is a test";
        string pattern = "is";
        foreach (var index in text.AllIndicesOf(pattern))
        {
            Console.WriteLine(index); // 2 5
        }
    }

Command line input in Python

Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.

#!/usr/bin/env python -i

How to check if current thread is not main thread

Looper.myLooper() == Looper.getMainLooper()

if this returns true, then you're on the UI thread!

Using OpenSSL what does "unable to write 'random state'" mean?

I have come accross this problem today on AWS Lambda. I created an environment variable RANDFILE = /tmp/.random

That did the trick.

Confirmation dialog on ng-click - AngularJS

HTML 5 Code Sample

<button href="#" ng-click="shoutOut()" confirmation-needed="Do you really want to
shout?">Click!</button>

AngularJs Custom Directive code-sample

var app = angular.module('mobileApp', ['ngGrid']);
app.directive('confirmationNeeded', function () {
    return {
    link: function (scope, element, attr) {
      var msg = attr.confirmationNeeded || "Are you sure?";
      var clickAction = attr.ngClick;
      element.bind('click',function (e) {
        scope.$eval(clickAction) if window.confirm(msg)
        e.stopImmediatePropagation();
        e.preventDefault();
       });
     }
    };
});

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

Just get column names from hive table

you could also do show columns in $table or see Hive, how do I retrieve all the database's tables columns for access to hive metadata

Use multiple custom fonts using @font-face?

Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.

Calculate percentage Javascript

_x000D_
_x000D_
<div id="contentse "><br>
      <h2>Percentage Calculator</h2>
    <form action="/charactercount" class="align-items-center" style="border: 1px solid #eee;padding:15px;" method="post" enctype="multipart/form-data" name="form">
        <input type="hidden" name="csrfmiddlewaretoken" value="NCBdw9beXfKV07Tc1epTBPqJ0gzfkmHNXKrAauE34n3jn4TGeL8Vv6miOShhqv6O">
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <br><div class="input-float" style="float: left;"> what is <input type="text" id="aa" required=""> % of <input type="text" id="ab"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatea()"> &nbsp; <input type="text" id="ac" readonly="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br style="clear: both;"> </div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <div class="input-float" style="float: left;"><input type="text" id="ba"> is what percent of <input type="text" id="bb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculateb()"> &nbsp; <input type="text" id="bc" readonly=""> &nbsp; % </div><br style="clear: both;"></div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        Find percentage change(increase/decrease) <br><br>
        <div class="input-float" style="float: left;">from <input type="text" id="ca"> to <input type="text" id="cb">&nbsp;?  </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatec()"> &nbsp; <input type="text" id="cc" readonly="">&nbsp;%</div><br style="clear: both;"></div>
    </form>
    </div>
_x000D_
_x000D_
_x000D_

Live example here: setool-percentage-calculator

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

php execute a background process

Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
    try{
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
        }
    }catch(Exception $e){}

    return false;
}

ValueError : I/O operation on closed file

Indent correctly; your for statement should be inside the with block:

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for w, c in p.items():
        cwriter.writerow(w + c)

Outside the with block, the file is closed.

>>> with open('/tmp/1', 'w') as f:
...     print(f.closed)
... 
False
>>> print(f.closed)
True

Algorithm to compare two images

If you're willing to consider a different approach altogether to detecting illegal copies of your images, you could consider watermarking. (from 1.4)

...inserts copyright information into the digital object without the loss of quality. Whenever the copyright of a digital object is in question, this information is extracted to identify the rightful owner. It is also possible to encode the identity of the original buyer along with the identity of the copyright holder, which allows tracing of any unauthorized copies.

While it's also a complex field, there are techniques that allow the watermark information to persist through gross image alteration: (from 1.9)

... any signal transform of reasonable strength cannot remove the watermark. Hence a pirate willing to remove the watermark will not succeed unless they debase the document too much to be of commercial interest.

of course, the faq calls implementing this approach: "...very challenging" but if you succeed with it, you get a high confidence of whether the image is a copy or not, rather than a percentage likelihood.

What linux shell command returns a part of a string?

In bash you can try this:

stringZ=abcABC123ABCabc
#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

Liquibase lock - reasons?

You can safely delete the table manually or using query. It will be recreated automatically.

DROP TABLE DATABASECHANGELOGLOCK;

Where is SQL Server Management Studio 2012?

I uninstalled all parts of SQL Server 2012 using Control Panel in Windows and then reinstalled (choosing "All Features"). Now it works!

Use Mockito to mock some methods but not others

Partial mocking of a class is also supported via Spy in mockito

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls real methods
spy.add("one");
spy.add("two");

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

Check the 1.10.19 and 2.7.22 docs for detailed explanation.

Upgrading React version and it's dependencies by reading package.json

you can update all of the dependencies to their latest version by npm update

Error in plot.new() : figure margins too large, Scatter plot

If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.

Moreover Execute the command

graphics.off()

VB.NET Switch Statement GoTo Case

you should declare label first use this :

    Select Case parameter 
        Case "userID"
                    ' does something here.
            Case "packageID"
                    ' does something here.
            Case "mvrType" 
                    If otherFactor Then 
                            ' does something here. 
                    Else 
                            GoTo else
                    End If 

            Case Else 
else :
                    ' does some processing... 
                    Exit Select 
    End Select

Retain precision with double in Java

If you have no choice other than using double values, can use the below code.

public static double sumDouble(double value1, double value2) {
    double sum = 0.0;
    String value1Str = Double.toString(value1);
    int decimalIndex = value1Str.indexOf(".");
    int value1Precision = 0;
    if (decimalIndex != -1) {
        value1Precision = (value1Str.length() - 1) - decimalIndex;
    }

    String value2Str = Double.toString(value2);
    decimalIndex = value2Str.indexOf(".");
    int value2Precision = 0;
    if (decimalIndex != -1) {
        value2Precision = (value2Str.length() - 1) - decimalIndex;
    }

    int maxPrecision = value1Precision > value2Precision ? value1Precision : value2Precision;
    sum = value1 + value2;
    String s = String.format("%." + maxPrecision + "f", sum);
    sum = Double.parseDouble(s);
    return sum;
}

How to get a single value from FormGroup

for Angular 6+ and >=RC.6

.html

<form [formGroup]="formGroup">
  <input type="text" formControlName="myName">
</form>

.ts

public formGroup: FormGroup;
this.formGroup.value.myName

should also work.

Is it possible that one domain name has multiple corresponding IP addresses?

You can do it. That is what big guys do as well.

First query:

» host google.com 
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229

Next query:

» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238

As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.

Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.

How to compare two double values in Java?

You can use Double.compare; It compares the two specified double values.

remove double quotes from Json return data using Jquery

You can simple try String(); to remove the quotes.

Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp

Thank me later.

PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.

Cocoa: What's the difference between the frame and the bounds?

Let me add my 5 cents.

Frame is used by the view's parent view to place it inside the parent view.

Bounds is used by the view itself to place it's own content (like a scroll view does while scrolling). See also clipsToBounds. Bounds also can be used to zoom in/out content of the view.

Analogy:
Frame ~ TV screen
Bounds ~ Camera (zoom, move, rotate)

How to install package from github repo in Yarn

You can add any Git repository (or tarball) as a dependency to yarn by specifying the remote URL (either HTTPS or SSH):

yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.

Here are some examples:

yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0  [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]

(Note: Fancybox v2.6.1 isn't available in the Git version.)

To support both npm and yarn, you can use the git+url syntax:

git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch

List of all special characters that need to be escaped in a regex

Assuming that you have and trust (to be authoritative) the list of escape characters Java regex uses (would be nice if these characters were exposed in some Pattern class member) you can use the following method to escape the character if it is indeed necessary:

private static final char[] escapeChars = { '<', '(', '[', '{', '\\', '^', '-', '=', '$', '!', '|', ']', '}', ')', '?', '*', '+', '.', '>' };

private static String regexEscape(char character) {
    for (char escapeChar : escapeChars) {
        if (character == escapeChar) {
            return "\\" + character;
        }
    }
    return String.valueOf(character);
}

How to remove the default arrow icon from a dropdown list (select element)?

Simple way to remove drop down arrow from select

_x000D_
_x000D_
select {_x000D_
  /* for Firefox */_x000D_
  -moz-appearance: none;_x000D_
  /* for Chrome */_x000D_
  -webkit-appearance: none;_x000D_
}_x000D_
_x000D_
/* For IE10 */_x000D_
select::-ms-expand {_x000D_
  display: none;_x000D_
}
_x000D_
<select>_x000D_
  <option>2000</option>_x000D_
  <option>2001</option>_x000D_
  <option>2002</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

You have not concluded your merge (MERGE_HEAD exists)

I resolved conflicts and also committed but still getting this error message on git push

All conflicts fixed but you are still merging.
(use "git commit" to conclude merge)

I did these steps to resolve error:

rm -rf .git/MERGE*
git pull origin branch_name 
git push origin branch_name

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

Select All as default value for Multivalue parameter

Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.

How to convert float to int with Java

Use Math.round(value) then after type cast it to integer.

float a = 8.61f;
int b = (int)Math.round(a);

iterating over and removing from a map

Use a real iterator.

Iterator<Object> it = map.keySet().iterator();

while (it.hasNext())
{
  it.next();
  if (something)
    it.remove();
 }

Actually, you might need to iterate over the entrySet() instead of the keySet() to make that work.

Center image horizontally within a div

To center an image horizontally, this works:

<p style="text-align:center"><img src=""></p>

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Here is another way to reproduce this error in Python2.7 with numpy:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)   #note the lack of tuple format for a and b
print(c) 

The np.concatenate method produces an error:

TypeError: only length-1 arrays can be converted to Python scalars

If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b))  #surround a and b with parens, packaging them as a tuple
print(c) 

Then it prints:

[1 2 3 4 5 6]

What's going on here?

That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".

In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

JavaFX open new window

The code below worked for me I used part of the code above inside the button class.

public Button signupB;

public void handleButtonClick (){

    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
        /*
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 630, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }

}

}

jQuery remove special characters from string and more

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I actually prefer to use the display name for the placeholder text majority of the time. Here is an example of using the DisplayName:

  @Html.TextBoxFor(x => x.FirstName, true, null, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.FirstName) })

How to generate a random integer number from within a range

While Ryan is correct, the solution can be much simpler based on what is known about the source of the randomness. To re-state the problem:

  • There is a source of randomness, outputting integer numbers in range [0, MAX) with uniform distribution.
  • The goal is to produce uniformly distributed random integer numbers in range [rmin, rmax] where 0 <= rmin < rmax < MAX.

In my experience, if the number of bins (or "boxes") is significantly smaller than the range of the original numbers, and the original source is cryptographically strong - there is no need to go through all that rigamarole, and simple modulo division would suffice (like output = rnd.next() % (rmax+1), if rmin == 0), and produce random numbers that are distributed uniformly "enough", and without any loss of speed. The key factor is the randomness source (i.e., kids, don't try this at home with rand()).

Here's an example/proof of how it works in practice. I wanted to generate random numbers from 1 to 22, having a cryptographically strong source that produced random bytes (based on Intel RDRAND). The results are:

Rnd distribution test (22 boxes, numbers of entries in each box):     
 1: 409443    4.55%
 2: 408736    4.54%
 3: 408557    4.54%
 4: 409125    4.55%
 5: 408812    4.54%
 6: 409418    4.55%
 7: 408365    4.54%
 8: 407992    4.53%
 9: 409262    4.55%
10: 408112    4.53%
11: 409995    4.56%
12: 409810    4.55%
13: 409638    4.55%
14: 408905    4.54%
15: 408484    4.54%
16: 408211    4.54%
17: 409773    4.55%
18: 409597    4.55%
19: 409727    4.55%
20: 409062    4.55%
21: 409634    4.55%
22: 409342    4.55%   
total: 100.00%

This is as close to uniform as I need for my purpose (fair dice throw, generating cryptographically strong codebooks for WWII cipher machines such as http://users.telenet.be/d.rijmenants/en/kl-7sim.htm, etc). The output does not show any appreciable bias.

Here's the source of cryptographically strong (true) random number generator: Intel Digital Random Number Generator and a sample code that produces 64-bit (unsigned) random numbers.

int rdrand64_step(unsigned long long int *therand)
{
  unsigned long long int foo;
  int cf_error_status;

  asm("rdrand %%rax; \
        mov $1,%%edx; \
        cmovae %%rax,%%rdx; \
        mov %%edx,%1; \
        mov %%rax, %0;":"=r"(foo),"=r"(cf_error_status)::"%rax","%rdx");
        *therand = foo;
  return cf_error_status;
}

I compiled it on Mac OS X with clang-6.0.1 (straight), and with gcc-4.8.3 using "-Wa,q" flag (because GAS does not support these new instructions).

Limit results in jQuery UI Autocomplete

here is what I used

.ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden;}

The overflow auto so the scroll bar will not show when it's not supposed to.

How to style components using makeStyles and still have lifecycle methods in Material UI?

Hi instead of using hook API, you should use Higher-order component API as mentioned here

I'll modify the example in the documentation to suit your need for class component

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

class HigherOrderComponentUsageExample extends React.Component {
  
  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>This component is passed to an HOC</Button>
      );
  }
}

HigherOrderComponentUsageExample.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

Notepad++ Multi editing

You can add/edit content on multiple lines by using control button. This is multi edit feature in Notepad++, we need to enable it from settings. Press and hold control, select places where you want to enter text, release control and start typing, this will update the text at all the places selected previously.

enter image description here

Ref: http://notepad-plus-plus.org/features/multi-editing.html

Use ASP.NET MVC validation with jquery ajax?

Here's a rather simple solution:

In the controller we return our errors like this:

if (!ModelState.IsValid)
        {
            return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
        }

Here's some of the client script:

function displayValidationErrors(errors)
{
    var $ul = $('div.validation-summary-valid.text-danger > ul');

    $ul.empty();
    $.each(errors, function (idx, errorMessage) {
        $ul.append('<li>' + errorMessage + '</li>');
    });
}

That's how we handle it via ajax:

$.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
        var isSuccessful = (data['success']);

        if (isSuccessful) {
            $('#partial-container-steps').html(data['view']);
            initializePage();
        }
        else {
            var errors = data['errors'];

            displayValidationErrors(errors);
        }
    }
});

Also, I render partial views via ajax in the following way:

var view = this.RenderRazorViewToString(partialUrl, viewModel);
        return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);

RenderRazorViewToString method:

public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

How to distinguish mouse "click" and "drag"

from @Przemek 's answer,

_x000D_
_x000D_
function listenClickOnly(element, callback, threshold=10) {
  let drag = 0;
  element.addEventListener('mousedown', () => drag = 0);
  element.addEventListener('mousemove', () => drag++);
  element.addEventListener('mouseup', e => {
    if (drag<threshold) callback(e);
  });
}

listenClickOnly(
  document,
  () => console.log('click'),
  10
);
_x000D_
_x000D_
_x000D_

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

How to run Python script on terminal?

You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial: http://docs.python-guide.org/en/latest/starting/install3/osx/.

To run the program you can then copy and paste in this code:

python /Users/luca/Documents/python/gameover.py

Or you can go to the directory of the file with cd followed by the folder. When you are in the folder you can then python YourFile.py.

How to remove decimal part from a number in C#

Use Math.Round

int d = (int) Math.Round(a, 0);

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
    if (uiElement == null)
    {
        throw new ArgumentNullException("uiElement");
    }

    if (uiElement.InvokeRequired)
    {
        if (forceSynchronous)
        {
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
        else
        {
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
    }
    else
    {    
        if (uiElement.IsDisposed)
        {
            throw new ObjectDisposedException("Control is already disposed.");
        }

        updater();
    }
}

Consider the case where we're calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action... from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?

Disable eslint rules for folder

YAML version :

overrides:
  - files: *-tests.js
    rules:
      no-param-reassign: 0

Example of specific rules for mocha tests :

You can also set a specific env for a folder, like this :

overrides:
  - files: test/*-tests.js
    env:
      mocha: true

This configuration will fix error message about describe and it not defined, only for your test folder:

/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef

How do you open a file in C++?

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

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).

If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.

There is an /etc/ImageMagick/policy.xml file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).

If you're getting a ReadImage error as above, you can change the line to:

<policy domain="coder" rights="read" pattern="LABEL" />

which should fix the issue.

The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:

<policy domain="coder" rights="read|write" pattern="LABEL" />

...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).

How to import csv file in PHP?

PHP > 5.3 use fgetcsv() or str_getcsv(). Couldn't be simpler.

How to format string to money

Parse to your string to a decimal first.

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

How do we count rows using older versions of Hibernate (~2009)?

You could try count(*)

Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();

Where Books is the name off the class - not the table in the database.

Difference between left join and right join in SQL Server

I feel we may require AND condition in where clause of last figure of Outer Excluding JOIN so that we get the desired result of A Union B Minus A Interaction B. I feel query needs to be updated to

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL AND B.Key IS NULL

If we use OR , then we will get all the results of A Union B

error: command 'gcc' failed with exit status 1 while installing eventlet

I am using MacOS catalina 10.15.4. None of the posted solutions worked for me. What worked for me is:

 >> xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

>> env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2==2.8.4
Collecting psycopg2==2.8.4
  Using cached psycopg2-2.8.4.tar.gz (377 kB)
Installing collected packages: psycopg2
  Attempting uninstall: psycopg2
    Found existing installation: psycopg2 2.7.7
    Uninstalling psycopg2-2.7.7:
      Successfully uninstalled psycopg2-2.7.7
    Running setup.py install for psycopg2 ... done
Successfully installed psycopg2-2.8.4

use pip3 for python3

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

How do I dump an object's fields to the console?

If you're looking for just the instance variables in the object, this might be useful:

obj.instance_variables.map do |var|
  puts [var, obj.instance_variable_get(var)].join(":")
end

or as a one-liner for copy and pasting:

obj.instance_variables.map{|var| puts [var, obj.instance_variable_get(var)].join(":")}

MySQL config file location - redhat linux server

On RH systems, MySQL configuration file is located under /etc/my.cnf by default.

custom facebook share button

You can simply do something like...

...
<head>
...
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId            : 'your-app-id', // you need to create an facebook app
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v3.3'
    });
  };
</script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
</head>
<body>
...
<button id="share-btn"></button>
<!-- load jquery -->
<script>
    $('#share-btn').on('click', function () {
        FB.ui({
            method: 'share',
            href: location.href, // Current url
        }, function (response) { });
    });
</script>
</body>

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

How to test the type of a thrown exception in Jest

Try:

expect(t).rejects.toThrow()

Convert INT to VARCHAR SQL

Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job. Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length and usually default 10 is good enough for integer to string conversion.

SELECT LTRIM(ColumnName) FROM TableName

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

Convert from lowercase to uppercase all values in all character variables in dataframe

Alternatively, if you just want to convert one particular row to uppercase, use the code below:

df[[1]] <- toupper(df[[1]])

Update using LINQ to SQL

LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:

using(var ctx = new FooContext()) {
    var obj = ctx.Bars.Single(x=>x.Id == id);
    obj.SomeProp = 123;
    ctx.SubmitChanges();
}

Or write an SP that does the same in TSQL, and expose the SP through the data-context:

using(var ctx = new FooContext()) {
    ctx.UpdateBar(id, 123);
}

Run cURL commands from Windows console

If you are not into Cygwin, you can use native Windows builds. Some are here: curl Download Wizard.

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

Git: Remove committed file after push

Reset the file in a correct state, commit, and push again.

If you're sure nobody else has fetched your changes yet, you can use --amend when committing, to modify your previous commit (i.e. rewrite history), and then push. I think you'll have to use the -f option when pushing, to force the push, though.

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

How can I invert color using CSS?

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
  color: white;_x000D_
  mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

ASP.NET MVC JsonResult Date Format

I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

var myDate = new Date(myReceivedDate);

Here is my complete solution minus Steve Levithan's source, which you can download:

Controller:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}

Javascript:

<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

JQuery - File attributes

If #uploadedfile is an input with type "file" :

var file = $("#uploadedfile")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

Normally this would fire on the change event, like so:

$("#uploadedfile").on("change", function(){
   var file = this.files[0],
       fileName = file.name,
       fileSize = file.size;
   alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
   CustomFileHandlingFunction(file);
});

FIDDLE

Find commit by hash SHA in Git

git log -1 --format="%an %ae%n%cn %ce" a2c25061

The Pretty Formats section of the git show documentation contains

  • format:<string>

The format:<string> format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with %n instead of \n

The placeholders are:

  • %an: author name
  • %ae: author email
  • %cn: committer name
  • %ce: committer email

How can I show an element that has display: none in a CSS rule?

Because setting the div's display style property to "" doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.

You need to set it to something that has a value:

document.getElementById('mybox').style.display = "block";

What you're doing would work if you were replacing an inline style on the div, like this:

<div id="myBox" style="display: none;"></div>

document.getElementById('mybox').style.display = "";

Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.

How to use default Android drawables

To use the default android drawable resource, no need copy anything.. you can just import it first with..

import android.R;

but i will make your own resources will have an error if you want to use it. The error will be something like:

R. cannot be resolved

So, I prefer not to import android.R but import *my.own.package*.R;

then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

Difference between JSON.stringify and JSON.parse

JavaScript Object <-> JSON String


JSON.stringify() <-> JSON.parse()

JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse() -> String To Object.

Explanation: JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space

Backup a single table with its data from a database in sql server 2008

Put the table in its own filegroup. You can then use regular SQL Server built in backup to backup the filegroup in which in effect backs up the table.

To backup a filegroup see: https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-files-and-filegroups-sql-server

To create a table on a non-default filegroup (its easy) see: Create a table on a filegroup other than the default

How to find files modified in last x minutes (find -mmin does not work as expected)

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

Terminating a Java Program

  • Well, first System.exit(0) is used to terminate the program and having statements below it is not correct, although the compiler does not throw any errors.
  • a plain return; is used in a method of void return type to return the control of execution to its parent method.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Java - get the current class name?

Try using this this.getClass().getCanonicalName() or this.getClass().getSimpleName(). If it's an anonymous class, use this.getClass().getSuperclass().getName()

How to use a PHP class from another file?

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

How do I change Eclipse to use spaces instead of tabs?

As an augmentation to the other answers, on Mac OS X, the "Preferences" menu is under Eclipse, not Window (unlike Windows/Linux Eclipse distributions). Everything else is still the same as pointed out by other answers past this point.

IE: Java Formatter available under:

Eclipse >      | # Not Window!
Preferences >  |
Java >         |
Code Style >   |
Formatter      |

From here, edit the formatter and the tab policy can be set under "Indentation".

How to get the selected index of a RadioGroup in Android

Here is a Kotlin extension to get the correct position even if your group contains a TextView or any non-RadioButton.

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

Efficiently test if a port is open on Linux?

A surprise I found out recently is that Bash natively supports tcp connections as file descriptors. To use:

exec 6<>/dev/tcp/ip.addr.of.server/445
echo -e "GET / HTTP/1.0\n" >&6
cat <&6

I'm using 6 as the file descriptor because 0,1,2 are stdin, stdout, and stderr. 5 is sometimes used by Bash for child processes, so 3,4,6,7,8, and 9 should be safe.

As per the comment below, to test for listening on a local server in a script:

exec 6<>/dev/tcp/127.0.0.1/445 || echo "No one is listening!"
exec 6>&- # close output connection
exec 6<&- # close input connection

To determine if someone is listening, attempt to connect by loopback. If it fails, then the port is closed or we aren't allowed access. Afterwards, close the connection.

Modify this for your use case, such as sending an email, exiting the script on failure, or starting the required service.

Angular ui-grid dynamically calculate height of the grid

I like Tony approach. It works, but I decided to implement in different way. Here my comments:

1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.

By the way, ui-if was removed. Now you have ng-if build-in.

2) I prefer to write a service like this:

angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {

var factory = {};

factory.getGridHeight = function(gridOptions) {

    var length = gridOptions.data.length;
    var rowHeight = 30; // your row height
    var headerHeight = 40; // your header height
    var filterHeight = 40; // your filter height

    return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {

    return value.replace(unit, '');
}
return factory;

});

And then in the controller write the following:

  angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {

  ...

  // Execute this when you have $scope.gridData loaded...
  $scope.gridHeight = uiGridService.getGridHeight($scope.gridData);

And at the HTML file:

  <div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>

When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.

3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.

    $scope.gridData = {
        enableSorting: true,
        multiSelect: false,  
        enableRowSelection: true,
        showFooter: false,
        enableFiltering: true,    
        enableSelectAll: false,
        enableRowHeaderSelection: false, 
        enableGridMenu: true,
        noUnselect: true,
        expandableRowTemplate: 'subGrid.html',
        expandableRowHeight: 380,   // 10 rows * 30px + 40px (header) + 40px (filters)
        onRegisterApi: function(gridApi) {

            gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
                var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
                var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));

                if (row.isExpanded)
                {
                    height += changedRowHeight;                    
                }
                else
                {
                    height -= changedRowHeight;                    
                }

                $scope.jdeNewUserConflictsGridHeight = height + 'px';
            });
        },
        columnDefs :  [
                { field: 'GridField1', name: 'GridField1', enableFiltering: true }
        ]
    }

How do I specify unique constraint for multiple columns in MySQL?

This works for mysql version 5.5.32

ALTER TABLE  `tablename` ADD UNIQUE (`column1` ,`column2`);

"webxml attribute is required" error in Maven

If you are migrating from XML-based to Java-based configuration and you have removed the need for web.xml by implementing WebApplicationInitializer, simply remove the requirement for the web.xml file to be present.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        ... 
    </configuration>

Create a pointer to two-dimensional array

You want a pointer to the first element, so;

static uint8_t l_matrix[10][20];

void test(){
   uint8_t *matrix_ptr = l_matrix[0]; //wrong idea 
}

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

Create an ArrayList with multiple object types?

You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example, You will get below output:

Beginning....
Contents of array: [String, 1]
Size of the list: 2
This is not an Integer String
This is an Integer 1

package com.viswa.examples.programs;

import java.util.ArrayList;
import java.util.Arrays;

public class VarArrayListDemo {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        System.out.println(" Beginning....");

        ArrayList varTypeArray = new ArrayList();
        varTypeArray.add("String");
        varTypeArray.add(1); //Stored as Integer

        System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());

        Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
    }

    private static <T> void checkType(T t) {

        if (Integer.class.isInstance(t)) {
            System.out.println(" This is an Integer " + t);
        } else {
            System.out.println(" This is not an Integer" + t);
        }
    }

}

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

This is how, I have been using a random user agent from a list of nearlly 1000 fake user agents

from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, OperatingSystem
software_names = [SoftwareName.ANDROID.value]
operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value, OperatingSystem.MAC.value]   

user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=1000)

# Get list of user agents.
user_agents = user_agent_rotator.get_user_agents()

user_agent_random = user_agent_rotator.get_random_user_agent()

Example

print(user_agent_random)

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36

For more details visit this link

How do I do a not equal in Django queryset filtering?

There are three options:

  1. Chain exclude and filter

    results = Model.objects.exclude(a=True).filter(x=5)
    
  2. Use Q() objects and the ~ operator

    from django.db.models import Q
    object_list = QuerySet.filter(~Q(a=True), x=5)
    
  3. Register a custom lookup function

    from django.db.models import Lookup
    from django.db.models import Field
    
    @Field.register_lookup
    class NotEqual(Lookup):
        lookup_name = 'ne'
    
        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return '%s <> %s' % (lhs, rhs), params
    

    Which can the be used as usual:

    results = Model.objects.exclude(a=True, x__ne=5)
    

IPC performance: Named Pipe vs Socket

I would suggest you take the easy path first, carefully isolating the IPC mechanism so that you can change from socket to pipe, but I would definitely go with socket first. You should be sure IPC performance is a problem before preemptively optimizing.

And if you get in trouble because of IPC speed, I think you should consider switching to shared memory rather than going to pipe.

If you want to do some transfer speed testing, you should try socat, which is a very versatile program that allows you to create almost any kind of tunnel.

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

How to set up googleTest as a shared library on Linux

This will build and install both gtest and gmock 1.7.0:

mkdir /tmp/googleTestMock
tar -xvf googletest-release-1.7.0.tar.gz -C /tmp/googleTestMock
tar -xvf googlemock-release-1.7.0.tar.gz -C /tmp/googleTestMock
cd /tmp/googleTestMock
mv googletest-release-1.7.0 gtest
cd googlemock-release-1.7.0
cmake -DBUILD_SHARED_LIBS=ON .
make -j$(nproc)
sudo cp -a include/gmock /usr/include
sudo cp -a libgmock.so libgmock_main.so /usr/lib/
sudo cp -a ../gtest/include/gtest /usr/include
sudo cp -a gtest/libgtest.so gtest/libgtest_main.so /usr/lib/
sudo ldconfig

JavaScript: location.href to open in new window/tab?

If you want to use location.href to avoid popup problems, you can use an empty <a> ref and then use javascript to click it.

something like in HTML

<a id="anchorID" href="mynewurl" target="_blank"></a>

Then javascript click it as follows

document.getElementById("anchorID").click();

How do I check if a string contains another string in Swift?

Here is my first stab at this in the swift playground. I extend String by providing two new functions (contains and containsIgnoreCase)

extension String {
    func contains(other: String) -> Bool{
        var start = startIndex

        do{
            var subString = self[Range(start: start++, end: endIndex)]
            if subString.hasPrefix(other){
                return true
            }

        }while start != endIndex

        return false
    }

    func containsIgnoreCase(other: String) -> Bool{
        var start = startIndex

        do{
            var subString = self[Range(start: start++, end: endIndex)].lowercaseString
            if subString.hasPrefix(other.lowercaseString){
                return true
            }

        }while start != endIndex

        return false
    }
}

Use it like this

var sentence = "This is a test sentence"
sentence.contains("this")  //returns false
sentence.contains("This")  //returns true
sentence.containsIgnoreCase("this")  //returns true

"This is another test sentence".contains(" test ")    //returns true

I'd welcome any feedback :)

mySQL select IN range

To select data in numerical range you can use BETWEEN which is inclusive.

SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;

Scala best way of turning a Collection into a Map-by-key?

use map() on collection followed with toMap

val map = list.map(e => (e, e.length)).toMap

What are some ways of accessing Microsoft SQL Server from Linux?

I'd like to recommend Sqlectron. Besides being open source under MIT license it's multiplatform boosted by Electron. Its own definition is:

A simple and lightweight SQL client desktop with cross database and platform support

It currently supports PostgreSQL, MySQL, MS SQL Server, Cassandra and SQLite.

Bootstrap - 5 column layout

Copypastable version of wearesicc's 5 col solution with bootstrap variables:

.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: ($gutter / 2);
    padding-left: ($gutter / 2);
}

.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: $screen-sm) {
    .col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-md) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-lg) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}

How can I make an image transparent on Android?

The method setAlpha(int) from the type ImageView is deprecated.

Instead of

image.setImageAlpha(127);
//value: [0-255]. Where 0 is fully transparent and 255 is fully opaque.

Creating a JSON response using Django and Python

This is my preferred version using a class based view. Simply subclass the basic View and override the get()-method.

import json

class MyJsonView(View):

    def get(self, *args, **kwargs):
        resp = {'my_key': 'my value',}
        return HttpResponse(json.dumps(resp), mimetype="application/json" )

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Add BindingResult parameter in your method. For reference please my code below.

save(@ModelAttribute Employee employee,BindingResult bindingResult)

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

What's the difference between SortedList and SortedDictionary?

I cracked open Reflector to have a look at this as there seems to be a bit of confusion about SortedList. It is in fact not a binary search tree, it is a sorted (by key) array of key-value pairs. There is also a TKey[] keys variable which is sorted in sync with the key-value pairs and used to binary search.

Here is some source (targeting .NET 4.5) to backup my claims.

Private members

// Fields
private const int _defaultCapacity = 4;
private int _size;
[NonSerialized]
private object _syncRoot;
private IComparer<TKey> comparer;
private static TKey[] emptyKeys;
private static TValue[] emptyValues;
private KeyList<TKey, TValue> keyList;
private TKey[] keys;
private const int MaxArrayLength = 0x7fefffff;
private ValueList<TKey, TValue> valueList;
private TValue[] values;
private int version;

SortedList.ctor(IDictionary, IComparer)

public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer)
{
    if (dictionary == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
    }
    dictionary.Keys.CopyTo(this.keys, 0);
    dictionary.Values.CopyTo(this.values, 0);
    Array.Sort<TKey, TValue>(this.keys, this.values, comparer);
    this._size = dictionary.Count;
}

SortedList.Add(TKey, TValue) : void

public void Add(TKey key, TValue value)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
    if (num >= 0)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }
    this.Insert(~num, key, value);
}

SortedList.RemoveAt(int) : void

public void RemoveAt(int index)
{
    if ((index < 0) || (index >= this._size))
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this.keys, index + 1, this.keys, index, this._size - index);
        Array.Copy(this.values, index + 1, this.values, index, this._size - index);
    }
    this.keys[this._size] = default(TKey);
    this.values[this._size] = default(TValue);
    this.version++;
}

Create a new Ruby on Rails application using MySQL instead of SQLite

If you are using rails 3 or greater version

rails new your_project_name -d mysql

if you have earlier version

rails new -d mysql your_project_name

So before you create your project you need to find the rails version. that you can find by

rails -v

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

Reset select2 value and show placeholder

This solution work for me (Select2 4.0.13)

$('#select').on("select2:unselecting", function (e) {
   $(this).val('').trigger('change');
   e.preventDefault();
});

getMinutes() 0-9 - How to display two digit numbers?

I assume you would need the value as string. You could use the code below. It will always return give you the two digit minutes as string.

var date = new Date(date);
var min = date.getMinutes();

if (min < 10) {
min = '0' + min;
} else {
min = min + '';
}
console.log(min);

Hope this helps.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

Git: "Corrupt loose object"

Try

git stash

This worked for me. It stashes anything you haven't committed and that got around the problem.

How can I list all of the files in a directory with Perl?

This will list Everything (including sub directories) from the directory you specify, in order, and with the attributes. I have spent days looking for something to do this, and I took parts from this entire discussion, and a little of my own, and put it together. ENJOY!!

#!/usr/bin/perl --
print qq~Content-type: text/html\n\n~;
print qq~<font face="arial" size="2">~;

use File::Find;

# find( \&wanted_tom, '/home/thomas/public_html'); # if you want just one website, uncomment this, and comment out the next line
find( \&wanted_tom, '/home');
exit;

sub wanted_tom {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat ($_);
$mode = (stat($_))[2];
$mode = substr(sprintf("%03lo", $mode), -3);

if (-d $File::Find::name) {
print "<br><b>--DIR $File::Find::name --ATTR:$mode</b><br>";
 } else {
print "$File::Find::name --ATTR:$mode<br>";
 }
  return;
}

How to implement a tree data-structure in Java?

There are a couple of tree data structures in Java, such as DefaultMutableTreeNode in JDK Swing, Tree in Stanford parser package, and other toy codes. But none of these are sufficient yet small enough for general purpose.

Java-tree project attempts to provide another general-purpose tree data structure in Java. The difference between this and others are

  • Totally free. You can use it anywhere (except in your homework :P)
  • Small but general enough. I put everything of the data structure in one class file, so it would be easy to copy/paste.
  • Not just a toys. I am aware of dozens of Java tree codes that can only handle binary trees or limited operations. This TreeNode is much more than that. It provides different ways of visiting nodes, such as preorder, postorder, breadthfirst, leaves, path to root, etc. Moreover, iterators are provided too for the sufficiency.
  • More utils will be added. I am willing to add more operations to make this project comprehensive, especially if you send a request through github.

Python - 'ascii' codec can't decode byte

You can try this

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

Or

You can also try following

Add following line at top of your .py file.

# -*- coding: utf-8 -*- 

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

how to get value of selected item in autocomplete

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('blur', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

How to use multiple databases in Laravel

Also you can use postgres fdw system

https://www.postgresql.org/docs/9.5/postgres-fdw.html

You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.

Best way to parseDouble with comma as decimal separator?

You of course need to use the correct locale. This question will help.

How to change the font on the TextView?

I finally got a very easy solution to this.

  1. use these Support libraries in app level gradle,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. then create a directory named "font" inside the res folder

  3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
  4. After that, reference that font from xml like this

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    

In this example, times_new_roman_test is a font ttf file from that font directory

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

Launch programs whose path contains spaces

You van use Exec

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Exec("c:\Program Files\Mozilla Firefox\firefox.exe")
Set objShell = Nothing

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

What is the default text size on Android?

Default values in appcompat-v7

<dimen name="abc_text_size_body_1_material">14sp</dimen>
<dimen name="abc_text_size_body_2_material">14sp</dimen>
<dimen name="abc_text_size_button_material">14sp</dimen>
<dimen name="abc_text_size_caption_material">12sp</dimen>
<dimen name="abc_text_size_display_1_material">34sp</dimen>
<dimen name="abc_text_size_display_2_material">45sp</dimen>
<dimen name="abc_text_size_display_3_material">56sp</dimen>
<dimen name="abc_text_size_display_4_material">112sp</dimen>
<dimen name="abc_text_size_headline_material">24sp</dimen>
<dimen name="abc_text_size_large_material">22sp</dimen>
<dimen name="abc_text_size_medium_material">18sp</dimen>
<dimen name="abc_text_size_menu_material">16sp</dimen>
<dimen name="abc_text_size_small_material">14sp</dimen>
<dimen name="abc_text_size_subhead_material">16sp</dimen>
<dimen name="abc_text_size_subtitle_material_toolbar">16dp</dimen>
<dimen name="abc_text_size_title_material">20sp</dimen>
<dimen name="abc_text_size_title_material_toolbar">20dp</dimen>

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Kotlin? Here we go:

android {

    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)

        kapt {
            arguments {
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }

    buildTypes {
        // ... (buildTypes, compileOptions, etc)
    }
}

//...

Don't forget about plugin:

apply plugin: 'kotlin-kapt'

For more information about kotlin annotation processor please visit: Kotlin docs

sqlalchemy: how to join several tables by one query?

A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):

class User(Base):
    __tablename__ = 'users'
    email = Column(String, primary_key=True)
    name = Column(String)

class Document(Base):
    __tablename__ = "documents"
    name = Column(String, primary_key=True)
    author_email = Column(String, ForeignKey("users.email"))
    author = relation(User, backref='documents')

class DocumentsPermissions(Base):
    __tablename__ = "documents_permissions"
    id = Column(Integer, primary_key=True)
    readAllowed = Column(Boolean)
    writeAllowed = Column(Boolean)
    document_name = Column(String, ForeignKey("documents.name"))
    document = relation(Document, backref = 'permissions')

Then do a simple query with joins:

query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I came across this one while debugging a virtualmin/apache related error.

In my case, I am running virtualmin and had in my virtual machine's php.ini safe_mode=On.

In my Virtual Machine's error log, I was getting the fcgi Connection reset by peer: mod_fcgid: error reading data from FastCGI server

In my main apache error log I was getting: PHP Fatal error: Directive 'safe_mode' is no longer available in PHP in Unknown on line 0

In my case, I simply set safe_mode = Off in my php.ini and restarted apache.

stackoverflow.com/questions/18683177/where-to-start-with-deprecated-directive-safe-mode-on-line-0-in-apache-error

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

In Java, how to append a string more efficiently?

You can use StringBuffer or StringBuilder for this. Both are for dynamic string manipulation. StringBuffer is thread-safe where as StringBuilder is not.

Use StringBuffer in a multi-thread environment. But if it is single threaded StringBuilder is recommended and it is much faster than StringBuffer.

Uninstall / remove a Homebrew package including all its dependencies

brew rmtree doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew doesn't have this as a native command.

brew tap ggpeti/rmrec
brew rmrec pkgname

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

Finding the index of an item in a list

name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
    new_list.append(item[0])
print(new_list)
try:
    location= new_list.index(name)
except:
    location=-1
print (location)

This accounts for if the string is not in the list too, if it isn't in the list then location = -1

DataTrigger where value is NOT null?

Stop! No converter! I dont want to "sell" the library of this guy, but I hated the fact of doing converter everytime I wanted to compare stuff in XAML.

So with this library : https://github.com/Alex141/CalcBinding

you can do that [and a lot more] :

First, In the declaration of the windows/userControl :

<Windows....
     xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"
>

then, in the textblock

<TextBlock>
      <TextBlock.Style>
          <Style.Triggers>
          <DataTrigger Binding="{conv:Binding 'MyValue==null'}" Value="false">
             <Setter Property="Background" Value="#FF80C983"></Setter>
          </DataTrigger>
        </Style.Triggers>
      </TextBlock.Style>
    </TextBlock>

The magic part is the conv:Binding 'MYValue==null'. In fact, you could set any condition you wanted [look at the doc].

note that I am not a fan of third party. but this library is Free, and little impact (just add 2 .dll to the project).

"FATAL: Module not found error" using modprobe

Insert this in your Makefile

 $(MAKE) -C $(KDIR) M=$(PWD) modules_install                      

 it will install the module in the directory /lib/modules/<var>/extra/
 After make , insert module with modprobe module_name (without .ko extension)

OR

After your normal make, you copy module module_name.ko into   directory  /lib/modules/<var>/extra/

then do modprobe module_name (without .ko extension)

How do you make sure email you send programmatically is not automatically marked as spam?

Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.

Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.

Make sure that the IP-address that you're using is not on a blacklist

Make sure that the reply-to address is a valid, existing address.

Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" <[email protected]> ).

Monitor your abuse accounts, such as [email protected] and [email protected]. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.

Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.

That said, getting Hotmail to accept your emails remains a black art.

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

HashMaps and Null values?

It seems that you are trying to call a method with a Map parameter. So, to call with an empty person name the right approach should be

HashMap<String, String> options = new HashMap<String, String>();
options.put("name", null);  
Person person = sample.searchPerson(options);

Or you can do it like this

HashMap<String, String> options = new HashMap<String, String>();
Person person = sample.searchPerson(options);

Using

Person person = sample.searchPerson(null);

Could get you a null pointer exception. It all depends on the implementation of searchPerson() method.

Form onSubmit determine which submit button was pressed

OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.

<script language="javascript" type="text/javascript">

    var initiator = '';
    $(document).ready(function() {
        $(":submit").click(function() { initiator = this.name });
    });

</script>

Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.

~Spanky

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

Android Studio Gradle Already disposed Module

For me this happened when I removed a module and tried to build the project:

Simple solution was to Invalidate the cache & Restart.

Android Studio>File>Invalidate Caches>Invalidate & Restart