Programs & Examples On #Linq to lucene

Deserialize JSON string to c# object

I believe you are looking for this:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop

```

How to declare strings in C

You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.

The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const to avoid that).

Error: Cannot invoke an expression whose type lacks a call signature

Add a type to your variable and then return.

Eg:

const myVariable : string [] = ['hello', 'there'];

const result = myVaraible.map(x=> {
  return
  {
    x.id
  }
});

=> Important part is adding the string[] type etc:

Does C# have a String Tokenizer like Java's?

read this, split function has an overload takes an array consist of seperators http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx

how to run a winform from console application?

I recently wanted to do this and found that I was not happy with any of the answers here.

If you follow Marc's advice and set the output-type to Console Application there are two problems:

1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.

2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of "myprocess &").


If you leave the output-type as Windows Application, but correctly call AttachConsole, you don't get a second console window when invoked from a console and you don't get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).

However, this has two different problems:

1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program's output comes after the prompt and no new prompt is displayed when you're done. This looks a bit confusing, not to mention that your "console app" is running in the background and the user is free to execute other commands while it's running.

2) Stream redirection gets messed up as well, e.g. "myapp some parameters > somefile" fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.


After many hours of hunting and experimenting, I've come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It's a matter of picking which side effects are least annoying for your application's purposes.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

Use the getColor(Resources, int, Theme) method of the ResourcesCompat from the Android Support Library.

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

I think it reflect better your question than the getColor(Context, int) of the ContextCompat since you ask about Resources. Prior to API level 23, the theme will not be applied and the method calls through to getColor(int) but you'll not have the deprecated warning. The theme also may be null.

How to get current user who's accessing an ASP.NET application?

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Difference between setUp() and setUpBeforeClass()

setUpBeforeClass is run before any method execution right after the constructor (run only once)

setUp is run before each method execution

tearDown is run after each method execution

tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

How to limit the maximum value of a numeric field in a Django model?

Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:

#Imports
from django.core.exceptions import ValidationError      

class validate_range_or_null(object):
    compare = lambda self, a, b, c: a > c or a < b
    clean = lambda self, x: x
    message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
    code = 'limit_value'

    def __init__(self, limit_min, limit_max):
        self.limit_min = limit_min
        self.limit_max = limit_max

    def __call__(self, value):
        cleaned = self.clean(value)
        params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
        if value:  # make it optional, remove it to make required, or make required on the model
            if self.compare(cleaned, self.limit_min, self.limit_max):
                raise ValidationError(self.message, code=self.code, params=params)

And it can be used as such:

class YourModel(models.Model):

    ....
    no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])

The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.

Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.

Hope this helps :) More on Validators in Django.

PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.

In bash, how to store a return value in a variable?

Use the special bash variable "$?" like so:

function_output=$(my_function)
function_return_value=$?

How can I detect if this dictionary key exists in C#?

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... }

or TryGetValue:

dict.TryGetValue(key, out value);

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    row["HomeStreet"] = entry;
}

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    if (entry.Street != null)
    {
        row["HomeStreet"] = entry.Street.ToString();
    }
}

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

Check an integer value is Null in c#

Several things:

Age is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T> on MSDN for details.

?? is the null coalesce operator, not the ternary operator (actually called the conditional operator).

To check if a nullable type has a value use HasValue, or check directly against null:

if(Age.HasValue)
{
   // Yay, it does!
}

if(Age == null)
{
   // It is null :(
}

Why does using an Underscore character in a LIKE filter give me all the results?

In case people are searching how to do it in BigQuery:

  • An underscore "_" matches a single character or byte.

  • You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".

WHERE mycolumn LIKE '%\\_%'

Source: https://cloud.google.com/bigquery/docs/reference/standard-sql/operators

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

Adding attribute in jQuery

Add attribute as:

$('#Selector_id').attr('disabled',true);

How to run bootRun with spring profile via gradle task

Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application

Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:

$ ./gradlew bootRun --args='--spring.profiles.active=dev'

push() a two-dimensional array

In your case you can do that without using push at all:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

delete image from folder PHP

There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

Each image's display markup would contain a form something like this:

echo '<form method="post">';
  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
  echo '<input type="submit" value="Delete image" />';
echo '</form>';

...and at at the top of that same PHP file:

if (array_key_exists('delete_file', $_POST)) {
  $filename = $_POST['delete_file'];
  if (file_exists($filename)) {
    unlink($filename);
    echo 'File '.$filename.' has been deleted';
  } else {
    echo 'Could not delete '.$filename.', file does not exist';
  }
}
// existing code continues below...

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

Documentation and Related Reading

What is the best way to detect a mobile device?

I use this

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}

Declaring variable workbook / Worksheet vba

Lots of answers above! here is my take:

Sub kl()

    Dim wb As Workbook
    Dim ws As Worksheet

    Set ws = Sheets("name")
    Set wb = ThisWorkbook

With ws
    .Select
End With

End Sub

your first (perhaps accidental) mistake as we have all mentioned is "Sheet"... should be "Sheets"

The with block is useful because if you set wb to anything other than the current workbook, it will ececute properly

Convert timestamp to date in MySQL query

I did it with the 'date' function as described in here :

(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)

Is it possible to send an array with the Postman Chrome extension?

It is important to know, that the VALUE box is only allowed to contain a numeral value (no specifiers).

If you want to send e.g. an array of "messages" with Postman, each having a list of key/value pairs, enter e.g. messages[][reason] into the KEY box and the value of reason into the VALUE box:

enter image description here

The server will receive:

{"messages"=>[{"reason"=>"scrolled", "tabid"=>"2"}, {"reason"=>"reload", "tabid"=>"1"}], "endpoint"=>{}}

Angularjs: Get element in controller

Create custom directive

masterApp.directive('ngRenderCallback', function() {
    return {
        restrict: "A",
        link: function ($scope, element, attrs) {
            setTimeout(function(){ 
                $scope[attrs.ngEl] = element[0];
                $scope.$eval(attrs.ngRenderCallback);               
            }, 30);
        }
    }
});

code for html template

<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>

function in controller

$scope.fnRenderCarousel = function(elName){
    $($scope[elName]).carousel();
}

how to use DEXtoJar

  1. Download dex2jar https://code.google.com/p/dex2jar/downloads/list
  2. Run dex2jar on apk d2j-dex2jar.sh someApk.apk
  3. open jar file in JD GUI http://jd.benow.ca/

Follow this guide: https://code.google.com/p/dex2jar/wiki/UserGuide

--Update 10/11/2016--

Found this ClassyShark from Google's github pretty easy to view code from APK.

https://github.com/google/android-classyshark

// make sure that you downloaded release https://github.com/pxb1988/dex2jar/releases (for the ppl who coldnt find this link in /dex2jar/downloads/list

html button to send email

You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.

The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.

When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)

Confusing "duplicate identifier" Typescript error message

run the following command will fix this issue.

npm install @types/node --save-dev

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I had the same issue. My mistake was that I used @Service annotation on the Service Interface. The @Service annotation should be applied to the ServiceImpl class.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

-- I like this as the data type and the format remains consistent with a date time data type

;with cte as(
    select 
        cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
    from dbo.mytable cd 
    where utcdate between '2014-01-14' and '2014-01-15'
    group by
        cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

Checkbox for nullable boolean

When making an EditorTemplate for a model which contains a nullable bool...

  • Split the nullable bool into 2 booleans:

    // Foo is still a nullable boolean.
    public bool? Foo 
    {
        get 
        { 
            if (FooIsNull)
                return null;
    
            return FooCheckbox;  
        }
        set
        {
            FooIsNull   = (value == null);
            FooCheckbox = (value ?? false);
        }
    }
    
    // These contain the value of Foo. Public only so they are visible in Razor views.
    public bool FooIsNull { get; set; }
    public bool FooCheckbox { get; set; }
    
  • Within the editor template:

    @Html.HiddenFor(m => m.FooIsNull)
    
    @if (Model.FooIsNull)
    {
        // Null means "checkbox is hidden"
        @Html.HiddenFor(m => m.FooCheckbox)
    }
    else
    {
        @Html.CheckBoxFor(m => m.FooCheckbox)
    }
    
  • Do not postback the original property Foo, because that is now calculated from FooIsNull and FooCheckbox.

Cannot connect to local SQL Server with Management Studio

Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.

With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?

In my log I see entries like this...

Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]

As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.

How to print pandas DataFrame without index

To answer the "How to print dataframe without an index" question, you can set the index to be an array of empty strings (one for each row in the dataframe), like this:

blankIndex=[''] * len(df)
df.index=blankIndex

If we use the data from your post:

row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)

which would normally print out as:

   User ID           Enter Time  Activity Number
0      123  2014-07-08 00:09:00             1411
1      123  2014-07-08 00:49:00             1041
2      123  2014-07-08 00:09:00             1411

By creating an array with as many empty strings as there are rows in the data frame:

blankIndex=[''] * len(df)
df.index=blankIndex
print(df)

It will remove the index from the output:

  User ID           Enter Time  Activity Number
      123  2014-07-08 00:09:00             1411
      123  2014-07-08 00:49:00             1041
      123  2014-07-08 00:09:00             1411

And in Jupyter Notebooks would render as per this screenshot: Juptyer Notebooks dataframe with no index column

Numpy: find index of the elements within range

You can use np.clip() to achieve the same:

a = [1, 3, 5, 6, 9, 10, 14, 15, 56]  
np.clip(a,6,10)

However, it holds the values less than and greater than 6 and 10 respectively.

Convert a date format in PHP

If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');

Or, equivalently:

$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:

<?php
    $source = '2012-07-31';
    $date = new DateTime($source);
    echo $date->format('d.m.Y'); // 31.07.2012
    echo $date->format('d-m-Y'); // 31-07-2012
?>

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

How to download a file from my server using SSH (using PuTTY on Windows)

try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop

Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.

Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop

How do I cancel form submission in submit button onclick event?

use onclick='return btnClick();'

and

function btnClick() {
    return validData();
}

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

Submit HTML form on self page

You can leave action attribute blank. The form will automatically submit itself in the same page.

<form action="">

According to the w3c specification, action attribute must be non-empty valid url in general. There is also an explanation for some situations in which the action attribute may be left empty.

The action of an element is the value of the element’s formaction attribute, if the element is a Submit Button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.

So they both still valid and works:

<form action="">
<form action="FULL_URL_STRING_OF_CURRENT_PAGE">

If you are sure your audience is using html5 browsers, you can even omit the action attribute:

<form>

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

Replace console output in Python

It can be done without using the sys library if we look at the print() function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here is my code:

def update(n):
    for i in range(n):
        print("i:",i,sep='',end="\r",flush=True)
        #time.sleep(1)

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

Element count of an array in C++

Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

In contexts where arr is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).

Sorry for the trivial question, I am a Java dev and I am rather new to C++.

C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[] in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size() with this class where you would use .length in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)

How can I output leading zeros in Ruby?

Can't you just use string formatting of the value before you concat the filename?

"%03d" % number

Adding days to $Date in PHP

If you're using PHP 5.3, you can use a DateTime object and its add method:

$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');

Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D', 3 would be 'P3D', and so on).

Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):

$Date1 = '2010-09-17';
$Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
// var_dump($Date2) returns "2010-09-18"

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

What is lexical scope?

I normally learn by example, and here's a little something:

const lives = 0;

function catCircus () {
    this.lives = 1;
    const lives = 2;

    const cat1 = {
        lives: 5,
        jumps: () => {
            console.log(this.lives);
        }
    };
    cat1.jumps(); // 1
    console.log(cat1); // { lives: 5, jumps: [Function: jumps] }

    const cat2 = {
        lives: 5,
        jumps: () => {
            console.log(lives);
        }
    };
    cat2.jumps(); // 2
    console.log(cat2); // { lives: 5, jumps: [Function: jumps] }

    const cat3 = {
        lives: 5,
        jumps: () => {
            const lives = 3;
            console.log(lives);
        }
    };
    cat3.jumps(); // 3
    console.log(cat3); // { lives: 5, jumps: [Function: jumps] }

    const cat4 = {
        lives: 5,
        jumps: function () {
            console.log(lives);
        }
    };
    cat4.jumps(); // 2
    console.log(cat4); // { lives: 5, jumps: [Function: jumps] }

    const cat5 = {
        lives: 5,
        jumps: function () {
            var lives = 4;
            console.log(lives);
        }
    };
    cat5.jumps(); // 4
    console.log(cat5); // { lives: 5, jumps: [Function: jumps] }

    const cat6 = {
        lives: 5,
        jumps: function () {
            console.log(this.lives);
        }
    };
    cat6.jumps(); // 5
    console.log(cat6); // { lives: 5, jumps: [Function: jumps] }

    const cat7 = {
        lives: 5,
        jumps: function thrownOutOfWindow () {
            console.log(this.lives);
        }
    };
    cat7.jumps(); // 5
    console.log(cat7); // { lives: 5, jumps: [Function: thrownOutOfWindow] }
}

catCircus();

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

What is a stack trace, and how can I use it to debug my application errors?

In simple terms, a stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.

Simple Example

With the example given in the question, we can determine exactly where the exception was thrown in the application. Let's have a look at the stack trace:

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
        at com.example.myproject.Author.getBookTitles(Author.java:25)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

This is a very simple stack trace. If we start at the beginning of the list of "at ...", we can tell where our error happened. What we're looking for is the topmost method call that is part of our application. In this case, it's:

at com.example.myproject.Book.getTitle(Book.java:16)

To debug this, we can open up Book.java and look at line 16, which is:

15   public String getTitle() {
16      System.out.println(title.toString());
17      return title;
18   }

This would indicate that something (probably title) is null in the above code.

Example with a chain of exceptions

Sometimes applications will catch an Exception and re-throw it as the cause of another Exception. This typically looks like:

34   public void getBookIds(int id) {
35      try {
36         book.getId(id);    // this method it throws a NullPointerException on line 22
37      } catch (NullPointerException e) {
38         throw new IllegalStateException("A book has a null property", e)
39      }
40   }

This might give you a stack trace that looks like:

Exception in thread "main" java.lang.IllegalStateException: A book has a null property
        at com.example.myproject.Author.getBookIds(Author.java:38)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Caused by: java.lang.NullPointerException
        at com.example.myproject.Book.getId(Book.java:22)
        at com.example.myproject.Author.getBookIds(Author.java:36)
        ... 1 more

What's different about this one is the "Caused by". Sometimes exceptions will have multiple "Caused by" sections. For these, you typically want to find the "root cause", which will be one of the lowest "Caused by" sections in the stack trace. In our case, it's:

Caused by: java.lang.NullPointerException <-- root cause
        at com.example.myproject.Book.getId(Book.java:22) <-- important line

Again, with this exception we'd want to look at line 22 of Book.java to see what might cause the NullPointerException here.

More daunting example with library code

Usually stack traces are much more complex than the two examples above. Here's an example (it's a long one, but demonstrates several levels of chained exceptions):

javax.servlet.ServletException: Something bad happened
    at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: com.example.myproject.MyProjectServletException
    at com.example.myproject.MyServlet.doPost(MyServlet.java:169)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)
    ... 27 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [com.example.myproject.MyEntity]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2822)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689)
    at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344)
    at $Proxy19.save(Unknown Source)
    at com.example.myproject.MyEntityService.save(MyEntityService.java:59) <-- relevant call (see notes below)
    at com.example.myproject.MyServlet.doPost(MyServlet.java:164)
    ... 32 more
Caused by: java.sql.SQLException: Violation of unique constraint MY_ENTITY_UK_1: duplicate value(s) for column(s) MY_COLUMN in statement [...]
    at org.hsqldb.jdbc.Util.throwError(Unknown Source)
    at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
    ... 54 more

In this example, there's a lot more. What we're mostly concerned about is looking for methods that are from our code, which would be anything in the com.example.myproject package. From the second example (above), we'd first want to look down for the root cause, which is:

Caused by: java.sql.SQLException

However, all the method calls under that are library code. So we'll move up to the "Caused by" above it, and look for the first method call originating from our code, which is:

at com.example.myproject.MyEntityService.save(MyEntityService.java:59)

Like in previous examples, we should look at MyEntityService.java on line 59, because that's where this error originated (this one's a bit obvious what went wrong, since the SQLException states the error, but the debugging procedure is what we're after).

Convert NSDate to NSString

swift 4 answer

static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    let date = dateFormatter.date(from: strDate)
    return date!
}
public static func dateToString(inputdate : Date) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    return formatter.string(from: inputdate)

}

Is SQL syntax case sensitive?

In Sql Server it is an option. Turning it on sucks.

I'm not sure about MySql.

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

Add CSS to <head> with JavaScript?

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

http://jsbin.com/oqede3/edit

Find a value anywhere in a database

Here, very sweet and small solution:

1) create a store procedure:

create procedure get_table
@find_str varchar(50)
as 
begin
  declare @col_name varchar(500), @tab_name varchar(500);
  declare @find_tab TABLE(table_name varchar(100), column_name varchar(100));

  DECLARE tab_col cursor for 
  select C.name as 'col_name', T.name as tab_name
  from sys.tables as T
  left outer join sys.columns as C on  C.object_id=T.object_id
  left outer join sys.types as TP on  C.system_type_id=TP.system_type_id
  where type='U' 
  and TP.name in('text','ntext','varchar','char','nvarchar','nchar');

  open tab_col
  fetch next from tab_col into @col_name, @tab_name

  while @@FETCH_STATUS = 0
  begin        
    insert into @find_tab 
    exec('select ''' +  @tab_name + ''',''' + @col_name + ''' from ' + @tab_name + 
    ' where ' + @col_name + '=''' + @find_str + ''' group by ' + 
    @col_name + ' having count(*)>0');

    fetch next from tab_col into @col_name, @tab_name;
  end
  CLOSE tab_col;  
  DEALLOCATE tab_col; 
  select table_name, column_name from @find_tab;

end

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

2) call procedure by calling store procedure:
exec get_table 'serach_string';

How do I format a number with commas in T-SQL?

I'd recommend Replace in lieu of Substring to avoid string length issues:

REPLACE(CONVERT(varchar(20), (CAST(SUM(table.value) AS money)), 1), '.00', '')

Create listview in fragment android

I guess your app crashes because of NullPointerException.

Change this

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

to

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

assuming listview belongs to the fragment layout.

The rest of the code looks alright

Edit:

Well since you said it is not working i tried it myself

enter image description here

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

How can I select an element with multiple classes in jQuery?

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!


Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :

$('input[type="text"].code.red')

Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

Extension gd is missing from your system - laravel composer Update

For php 7.1

sudo apt-get install php7.1-gd

Cheers!

scp via java

jsCH has worked great for me. Below is an example of a method that will connect to sftp server and download files to specified directory. It is recommended to stay away from disabling StrictHostKeyChecking. Although a little bit more difficult to set up, for security reasons specifying the known hosts should be the norm.

jsch.setKnownHosts("C:\Users\test\known_hosts"); recommended

JSch.setConfig("StrictHostKeyChecking", "no"); - not recommended

import com.jcraft.jsch.*;
 public void downloadFtp(String userName, String password, String host, int port, String path) {


        Session session = null;
        Channel channel = null;
        try {
            JSch ssh = new JSch();
            JSch.setConfig("StrictHostKeyChecking", "no");
            session = ssh.getSession(userName, host, port);
            session.setPassword(password);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.get(path, "specify path to where you want the files to be output");
        } catch (JSchException e) {
            System.out.println(userName);
            e.printStackTrace();


        } catch (SftpException e) {
            System.out.println(userName);
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }

    }

How to set maximum fullscreen in vmware?

Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You can try and check for the referer, which should be the parent site if you're an iframe

you can do that like this:

var href = document.referrer;

MongoDB logging all queries

I made a command line tool to activate the profiler activity and see the logs in a "tail"able way: "mongotail".

But the more interesting feature (also like tail) is to see the changes in "real time" with the -f option, and occasionally filter the result with grep to find a particular operation.

See documentation and installation instructions in: https://github.com/mrsarm/mongotail

Displaying Windows command prompt output and redirecting it to a file

I’d like to expand a bit on Saxon Druce’s excellent answer.

As stated, you can redirect the output of an executable in the current directory like so:

powershell ".\something.exe | tee test.txt"

However, this only logs stdout to test.txt. It doesn’t also log stderr.

The obvious solution would be to use something like this:

powershell ".\something.exe 2>&1 | tee test.txt"

However, this won’t work for all something.exes. Some something.exes will interpret the 2>&1 as an argument and fail. The correct solution is to instead only have apostrophes around the something.exe and its switches and arguments, like so:

powershell ".\something.exe --switch1 --switch2 … arg1 arg2 …" 2>&1 | tee test.txt

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

You need to provide an absolute path, not a relative path.

Provide the full path to the /data directory you are trying to write to.

Setting Authorization Header of HttpClient

So the way to do it is the following,

httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", "Your Oauth token");

Interface/enum listing standard mime-type constants

I solved this with a static class:

@SuppressWarnings("serial")
public class MimeTypes {

    private static final HashMap<String, String> mimeTypes;

    static {
        mimeTypes = new HashMap<String, String>() {
            {
                put(".323", "text/h323");
                put(".3g2", "video/3gpp2");
                put(".3gp", "video/3gpp");
                put(".3gp2", "video/3gpp2");
                put(".3gpp", "video/3gpp");
                put(".7z", "application/x-7z-compressed");
                put(".aa", "audio/audible");
                put(".AAC", "audio/aac");
                put(".aaf", "application/octet-stream");
                put(".aax", "audio/vnd.audible.aax");
                put(".ac3", "audio/ac3");
                put(".aca", "application/octet-stream");
                put(".accda", "application/msaccess.addin");
                put(".accdb", "application/msaccess");
                put(".accdc", "application/msaccess.cab");
                put(".accde", "application/msaccess");
                put(".accdr", "application/msaccess.runtime");
                put(".accdt", "application/msaccess");
                put(".accdw", "application/msaccess.webapplication");
                put(".accft", "application/msaccess.ftemplate");
                put(".acx", "application/internet-property-stream");
                put(".AddIn", "text/xml");
                put(".ade", "application/msaccess");
                put(".adobebridge", "application/x-bridge-url");
                put(".adp", "application/msaccess");
                put(".ADT", "audio/vnd.dlna.adts");
                put(".ADTS", "audio/aac");
                put(".afm", "application/octet-stream");
                put(".ai", "application/postscript");
                put(".aif", "audio/x-aiff");
                put(".aifc", "audio/aiff");
                put(".aiff", "audio/aiff");
                put(".air", "application/vnd.adobe.air-application-installer-package+zip");
                put(".amc", "application/x-mpeg");
                put(".application", "application/x-ms-application");
                put(".art", "image/x-jg");
                put(".asa", "application/xml");
                put(".asax", "application/xml");
                put(".ascx", "application/xml");
                put(".asd", "application/octet-stream");
                put(".asf", "video/x-ms-asf");
                put(".ashx", "application/xml");
                put(".asi", "application/octet-stream");
                put(".asm", "text/plain");
                put(".asmx", "application/xml");
                put(".aspx", "application/xml");
                put(".asr", "video/x-ms-asf");
                put(".asx", "video/x-ms-asf");
                put(".atom", "application/atom+xml");
                put(".au", "audio/basic");
                put(".avi", "video/x-msvideo");
                put(".axs", "application/olescript");
                put(".bas", "text/plain");
                put(".bcpio", "application/x-bcpio");
                put(".bin", "application/octet-stream");
                put(".bmp", "image/bmp");
                put(".c", "text/plain");
                put(".cab", "application/octet-stream");
                put(".caf", "audio/x-caf");
                put(".calx", "application/vnd.ms-office.calx");
                put(".cat", "application/vnd.ms-pki.seccat");
                put(".cc", "text/plain");
                put(".cd", "text/plain");
                put(".cdda", "audio/aiff");
                put(".cdf", "application/x-cdf");
                put(".cer", "application/x-x509-ca-cert");
                put(".chm", "application/octet-stream");
                put(".class", "application/x-java-applet");
                put(".clp", "application/x-msclip");
                put(".cmx", "image/x-cmx");
                put(".cnf", "text/plain");
                put(".cod", "image/cis-cod");
                put(".config", "application/xml");
                put(".contact", "text/x-ms-contact");
                put(".coverage", "application/xml");
                put(".cpio", "application/x-cpio");
                put(".cpp", "text/plain");
                put(".crd", "application/x-mscardfile");
                put(".crl", "application/pkix-crl");
                put(".crt", "application/x-x509-ca-cert");
                put(".cs", "text/plain");
                put(".csdproj", "text/plain");
                put(".csh", "application/x-csh");
                put(".csproj", "text/plain");
                put(".css", "text/css");
                put(".csv", "text/csv");
                put(".cur", "application/octet-stream");
                put(".cxx", "text/plain");
                put(".dat", "application/octet-stream");
                put(".datasource", "application/xml");
                put(".dbproj", "text/plain");
                put(".dcr", "application/x-director");
                put(".def", "text/plain");
                put(".deploy", "application/octet-stream");
                put(".der", "application/x-x509-ca-cert");
                put(".dgml", "application/xml");
                put(".dib", "image/bmp");
                put(".dif", "video/x-dv");
                put(".dir", "application/x-director");
                put(".disco", "text/xml");
                put(".dll", "application/x-msdownload");
                put(".dll.config", "text/xml");
                put(".dlm", "text/dlm");
                put(".doc", "application/msword");
                put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
                put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                put(".dot", "application/msword");
                put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
                put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
                put(".dsp", "application/octet-stream");
                put(".dsw", "text/plain");
                put(".dtd", "text/xml");
                put(".dtsConfig", "text/xml");
                put(".dv", "video/x-dv");
                put(".dvi", "application/x-dvi");
                put(".dwf", "drawing/x-dwf");
                put(".dwp", "application/octet-stream");
                put(".dxr", "application/x-director");
                put(".eml", "message/rfc822");
                put(".emz", "application/octet-stream");
                put(".eot", "application/octet-stream");
                put(".eps", "application/postscript");
                put(".etl", "application/etl");
                put(".etx", "text/x-setext");
                put(".evy", "application/envoy");
                put(".exe", "application/octet-stream");
                put(".exe.config", "text/xml");
                put(".fdf", "application/vnd.fdf");
                put(".fif", "application/fractals");
                put(".filters", "Application/xml");
                put(".fla", "application/octet-stream");
                put(".flr", "x-world/x-vrml");
                put(".flv", "video/x-flv");
                put(".fsscript", "application/fsharp-script");
                put(".fsx", "application/fsharp-script");
                put(".generictest", "application/xml");
                put(".gif", "image/gif");
                put(".group", "text/x-ms-group");
                put(".gsm", "audio/x-gsm");
                put(".gtar", "application/x-gtar");
                put(".gz", "application/x-gzip");
                put(".h", "text/plain");
                put(".hdf", "application/x-hdf");
                put(".hdml", "text/x-hdml");
                put(".hhc", "application/x-oleobject");
                put(".hhk", "application/octet-stream");
                put(".hhp", "application/octet-stream");
                put(".hlp", "application/winhlp");
                put(".hpp", "text/plain");
                put(".hqx", "application/mac-binhex40");
                put(".hta", "application/hta");
                put(".htc", "text/x-component");
                put(".htm", "text/html");
                put(".html", "text/html");
                put(".htt", "text/webviewhtml");
                put(".hxa", "application/xml");
                put(".hxc", "application/xml");
                put(".hxd", "application/octet-stream");
                put(".hxe", "application/xml");
                put(".hxf", "application/xml");
                put(".hxh", "application/octet-stream");
                put(".hxi", "application/octet-stream");
                put(".hxk", "application/xml");
                put(".hxq", "application/octet-stream");
                put(".hxr", "application/octet-stream");
                put(".hxs", "application/octet-stream");
                put(".hxt", "text/html");
                put(".hxv", "application/xml");
                put(".hxw", "application/octet-stream");
                put(".hxx", "text/plain");
                put(".i", "text/plain");
                put(".ico", "image/x-icon");
                put(".ics", "application/octet-stream");
                put(".idl", "text/plain");
                put(".ief", "image/ief");
                put(".iii", "application/x-iphone");
                put(".inc", "text/plain");
                put(".inf", "application/octet-stream");
                put(".inl", "text/plain");
                put(".ins", "application/x-internet-signup");
                put(".ipa", "application/x-itunes-ipa");
                put(".ipg", "application/x-itunes-ipg");
                put(".ipproj", "text/plain");
                put(".ipsw", "application/x-itunes-ipsw");
                put(".iqy", "text/x-ms-iqy");
                put(".isp", "application/x-internet-signup");
                put(".ite", "application/x-itunes-ite");
                put(".itlp", "application/x-itunes-itlp");
                put(".itms", "application/x-itunes-itms");
                put(".itpc", "application/x-itunes-itpc");
                put(".IVF", "video/x-ivf");
                put(".jar", "application/java-archive");
                put(".java", "application/octet-stream");
                put(".jck", "application/liquidmotion");
                put(".jcz", "application/liquidmotion");
                put(".jfif", "image/pjpeg");
                put(".jnlp", "application/x-java-jnlp-file");
                put(".jpb", "application/octet-stream");
                put(".jpe", "image/jpeg");
                put(".jpeg", "image/jpeg");
                put(".jpg", "image/jpeg");
                put(".js", "application/x-javascript");
                put(".json", "application/json");
                put(".jsx", "text/jscript");
                put(".jsxbin", "text/plain");
                put(".latex", "application/x-latex");
                put(".library-ms", "application/windows-library+xml");
                put(".lit", "application/x-ms-reader");
                put(".loadtest", "application/xml");
                put(".lpk", "application/octet-stream");
                put(".lsf", "video/x-la-asf");
                put(".lst", "text/plain");
                put(".lsx", "video/x-la-asf");
                put(".lzh", "application/octet-stream");
                put(".m13", "application/x-msmediaview");
                put(".m14", "application/x-msmediaview");
                put(".m1v", "video/mpeg");
                put(".m2t", "video/vnd.dlna.mpeg-tts");
                put(".m2ts", "video/vnd.dlna.mpeg-tts");
                put(".m2v", "video/mpeg");
                put(".m3u", "audio/x-mpegurl");
                put(".m3u8", "audio/x-mpegurl");
                put(".m4a", "audio/m4a");
                put(".m4b", "audio/m4b");
                put(".m4p", "audio/m4p");
                put(".m4r", "audio/x-m4r");
                put(".m4v", "video/x-m4v");
                put(".mac", "image/x-macpaint");
                put(".mak", "text/plain");
                put(".man", "application/x-troff-man");
                put(".manifest", "application/x-ms-manifest");
                put(".map", "text/plain");
                put(".master", "application/xml");
                put(".mda", "application/msaccess");
                put(".mdb", "application/x-msaccess");
                put(".mde", "application/msaccess");
                put(".mdp", "application/octet-stream");
                put(".me", "application/x-troff-me");
                put(".mfp", "application/x-shockwave-flash");
                put(".mht", "message/rfc822");
                put(".mhtml", "message/rfc822");
                put(".mid", "audio/mid");
                put(".midi", "audio/mid");
                put(".mix", "application/octet-stream");
                put(".mk", "text/plain");
                put(".mmf", "application/x-smaf");
                put(".mno", "text/xml");
                put(".mny", "application/x-msmoney");
                put(".mod", "video/mpeg");
                put(".mov", "video/quicktime");
                put(".movie", "video/x-sgi-movie");
                put(".mp2", "video/mpeg");
                put(".mp2v", "video/mpeg");
                put(".mp3", "audio/mpeg");
                put(".mp4", "video/mp4");
                put(".mp4v", "video/mp4");
                put(".mpa", "video/mpeg");
                put(".mpe", "video/mpeg");
                put(".mpeg", "video/mpeg");
                put(".mpf", "application/vnd.ms-mediapackage");
                put(".mpg", "video/mpeg");
                put(".mpp", "application/vnd.ms-project");
                put(".mpv2", "video/mpeg");
                put(".mqv", "video/quicktime");
                put(".ms", "application/x-troff-ms");
                put(".msi", "application/octet-stream");
                put(".mso", "application/octet-stream");
                put(".mts", "video/vnd.dlna.mpeg-tts");
                put(".mtx", "application/xml");
                put(".mvb", "application/x-msmediaview");
                put(".mvc", "application/x-miva-compiled");
                put(".mxp", "application/x-mmxp");
                put(".nc", "application/x-netcdf");
                put(".nsc", "video/x-ms-asf");
                put(".nws", "message/rfc822");
                put(".ocx", "application/octet-stream");
                put(".oda", "application/oda");
                put(".odc", "text/x-ms-odc");
                put(".odh", "text/plain");
                put(".odl", "text/plain");
                put(".odp", "application/vnd.oasis.opendocument.presentation");
                put(".ods", "application/oleobject");
                put(".odt", "application/vnd.oasis.opendocument.text");
                put(".one", "application/onenote");
                put(".onea", "application/onenote");
                put(".onepkg", "application/onenote");
                put(".onetmp", "application/onenote");
                put(".onetoc", "application/onenote");
                put(".onetoc2", "application/onenote");
                put(".orderedtest", "application/xml");
                put(".osdx", "application/opensearchdescription+xml");
                put(".p10", "application/pkcs10");
                put(".p12", "application/x-pkcs12");
                put(".p7b", "application/x-pkcs7-certificates");
                put(".p7c", "application/pkcs7-mime");
                put(".p7m", "application/pkcs7-mime");
                put(".p7r", "application/x-pkcs7-certreqresp");
                put(".p7s", "application/pkcs7-signature");
                put(".pbm", "image/x-portable-bitmap");
                put(".pcast", "application/x-podcast");
                put(".pct", "image/pict");
                put(".pcx", "application/octet-stream");
                put(".pcz", "application/octet-stream");
                put(".pdf", "application/pdf");
                put(".pfb", "application/octet-stream");
                put(".pfm", "application/octet-stream");
                put(".pfx", "application/x-pkcs12");
                put(".pgm", "image/x-portable-graymap");
                put(".pic", "image/pict");
                put(".pict", "image/pict");
                put(".pkgdef", "text/plain");
                put(".pkgundef", "text/plain");
                put(".pko", "application/vnd.ms-pki.pko");
                put(".pls", "audio/scpls");
                put(".pma", "application/x-perfmon");
                put(".pmc", "application/x-perfmon");
                put(".pml", "application/x-perfmon");
                put(".pmr", "application/x-perfmon");
                put(".pmw", "application/x-perfmon");
                put(".png", "image/png");
                put(".pnm", "image/x-portable-anymap");
                put(".pnt", "image/x-macpaint");
                put(".pntg", "image/x-macpaint");
                put(".pnz", "image/png");
                put(".pot", "application/vnd.ms-powerpoint");
                put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
                put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
                put(".ppa", "application/vnd.ms-powerpoint");
                put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
                put(".ppm", "image/x-portable-pixmap");
                put(".pps", "application/vnd.ms-powerpoint");
                put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
                put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
                put(".ppt", "application/vnd.ms-powerpoint");
                put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
                put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                put(".prf", "application/pics-rules");
                put(".prm", "application/octet-stream");
                put(".prx", "application/octet-stream");
                put(".ps", "application/postscript");
                put(".psc1", "application/PowerShell");
                put(".psd", "application/octet-stream");
                put(".psess", "application/xml");
                put(".psm", "application/octet-stream");
                put(".psp", "application/octet-stream");
                put(".pub", "application/x-mspublisher");
                put(".pwz", "application/vnd.ms-powerpoint");
                put(".qht", "text/x-html-insertion");
                put(".qhtm", "text/x-html-insertion");
                put(".qt", "video/quicktime");
                put(".qti", "image/x-quicktime");
                put(".qtif", "image/x-quicktime");
                put(".qtl", "application/x-quicktimeplayer");
                put(".qxd", "application/octet-stream");
                put(".ra", "audio/x-pn-realaudio");
                put(".ram", "audio/x-pn-realaudio");
                put(".rar", "application/octet-stream");
                put(".ras", "image/x-cmu-raster");
                put(".rat", "application/rat-file");
                put(".rc", "text/plain");
                put(".rc2", "text/plain");
                put(".rct", "text/plain");
                put(".rdlc", "application/xml");
                put(".resx", "application/xml");
                put(".rf", "image/vnd.rn-realflash");
                put(".rgb", "image/x-rgb");
                put(".rgs", "text/plain");
                put(".rm", "application/vnd.rn-realmedia");
                put(".rmi", "audio/mid");
                put(".rmp", "application/vnd.rn-rn_music_package");
                put(".roff", "application/x-troff");
                put(".rpm", "audio/x-pn-realaudio-plugin");
                put(".rqy", "text/x-ms-rqy");
                put(".rtf", "application/rtf");
                put(".rtx", "text/richtext");
                put(".ruleset", "application/xml");
                put(".s", "text/plain");
                put(".safariextz", "application/x-safari-safariextz");
                put(".scd", "application/x-msschedule");
                put(".sct", "text/scriptlet");
                put(".sd2", "audio/x-sd2");
                put(".sdp", "application/sdp");
                put(".sea", "application/octet-stream");
                put(".searchConnector-ms", "application/windows-search-connector+xml");
                put(".setpay", "application/set-payment-initiation");
                put(".setreg", "application/set-registration-initiation");
                put(".settings", "application/xml");
                put(".sgimb", "application/x-sgimb");
                put(".sgml", "text/sgml");
                put(".sh", "application/x-sh");
                put(".shar", "application/x-shar");
                put(".shtml", "text/html");
                put(".sit", "application/x-stuffit");
                put(".sitemap", "application/xml");
                put(".skin", "application/xml");
                put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
                put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
                put(".slk", "application/vnd.ms-excel");
                put(".sln", "text/plain");
                put(".slupkg-ms", "application/x-ms-license");
                put(".smd", "audio/x-smd");
                put(".smi", "application/octet-stream");
                put(".smx", "audio/x-smd");
                put(".smz", "audio/x-smd");
                put(".snd", "audio/basic");
                put(".snippet", "application/xml");
                put(".snp", "application/octet-stream");
                put(".sol", "text/plain");
                put(".sor", "text/plain");
                put(".spc", "application/x-pkcs7-certificates");
                put(".spl", "application/futuresplash");
                put(".src", "application/x-wais-source");
                put(".srf", "text/plain");
                put(".SSISDeploymentManifest", "text/xml");
                put(".ssm", "application/streamingmedia");
                put(".sst", "application/vnd.ms-pki.certstore");
                put(".stl", "application/vnd.ms-pki.stl");
                put(".sv4cpio", "application/x-sv4cpio");
                put(".sv4crc", "application/x-sv4crc");
                put(".svc", "application/xml");
                put(".swf", "application/x-shockwave-flash");
                put(".t", "application/x-troff");
                put(".tar", "application/x-tar");
                put(".tcl", "application/x-tcl");
                put(".testrunconfig", "application/xml");
                put(".testsettings", "application/xml");
                put(".tex", "application/x-tex");
                put(".texi", "application/x-texinfo");
                put(".texinfo", "application/x-texinfo");
                put(".tgz", "application/x-compressed");
                put(".thmx", "application/vnd.ms-officetheme");
                put(".thn", "application/octet-stream");
                put(".tif", "image/tiff");
                put(".tiff", "image/tiff");
                put(".tlh", "text/plain");
                put(".tli", "text/plain");
                put(".toc", "application/octet-stream");
                put(".tr", "application/x-troff");
                put(".trm", "application/x-msterminal");
                put(".trx", "application/xml");
                put(".ts", "video/vnd.dlna.mpeg-tts");
                put(".tsv", "text/tab-separated-values");
                put(".ttf", "application/octet-stream");
                put(".tts", "video/vnd.dlna.mpeg-tts");
                put(".txt", "text/plain");
                put(".u32", "application/octet-stream");
                put(".uls", "text/iuls");
                put(".user", "text/plain");
                put(".ustar", "application/x-ustar");
                put(".vb", "text/plain");
                put(".vbdproj", "text/plain");
                put(".vbk", "video/mpeg");
                put(".vbproj", "text/plain");
                put(".vbs", "text/vbscript");
                put(".vcf", "text/x-vcard");
                put(".vcproj", "Application/xml");
                put(".vcs", "text/plain");
                put(".vcxproj", "Application/xml");
                put(".vddproj", "text/plain");
                put(".vdp", "text/plain");
                put(".vdproj", "text/plain");
                put(".vdx", "application/vnd.ms-visio.viewer");
                put(".vml", "text/xml");
                put(".vscontent", "application/xml");
                put(".vsct", "text/xml");
                put(".vsd", "application/vnd.visio");
                put(".vsi", "application/ms-vsi");
                put(".vsix", "application/vsix");
                put(".vsixlangpack", "text/xml");
                put(".vsixmanifest", "text/xml");
                put(".vsmdi", "application/xml");
                put(".vspscc", "text/plain");
                put(".vss", "application/vnd.visio");
                put(".vsscc", "text/plain");
                put(".vssettings", "text/xml");
                put(".vssscc", "text/plain");
                put(".vst", "application/vnd.visio");
                put(".vstemplate", "text/xml");
                put(".vsto", "application/x-ms-vsto");
                put(".vsw", "application/vnd.visio");
                put(".vsx", "application/vnd.visio");
                put(".vtx", "application/vnd.visio");
                put(".wav", "audio/wav");
                put(".wave", "audio/wav");
                put(".wax", "audio/x-ms-wax");
                put(".wbk", "application/msword");
                put(".wbmp", "image/vnd.wap.wbmp");
                put(".wcm", "application/vnd.ms-works");
                put(".wdb", "application/vnd.ms-works");
                put(".wdp", "image/vnd.ms-photo");
                put(".webarchive", "application/x-safari-webarchive");
                put(".webtest", "application/xml");
                put(".wiq", "application/xml");
                put(".wiz", "application/msword");
                put(".wks", "application/vnd.ms-works");
                put(".WLMP", "application/wlmoviemaker");
                put(".wlpginstall", "application/x-wlpg-detect");
                put(".wlpginstall3", "application/x-wlpg3-detect");
                put(".wm", "video/x-ms-wm");
                put(".wma", "audio/x-ms-wma");
                put(".wmd", "application/x-ms-wmd");
                put(".wmf", "application/x-msmetafile");
                put(".wml", "text/vnd.wap.wml");
                put(".wmlc", "application/vnd.wap.wmlc");
                put(".wmls", "text/vnd.wap.wmlscript");
                put(".wmlsc", "application/vnd.wap.wmlscriptc");
                put(".wmp", "video/x-ms-wmp");
                put(".wmv", "video/x-ms-wmv");
                put(".wmx", "video/x-ms-wmx");
                put(".wmz", "application/x-ms-wmz");
                put(".wpl", "application/vnd.ms-wpl");
                put(".wps", "application/vnd.ms-works");
                put(".wri", "application/x-mswrite");
                put(".wrl", "x-world/x-vrml");
                put(".wrz", "x-world/x-vrml");
                put(".wsc", "text/scriptlet");
                put(".wsdl", "text/xml");
                put(".wvx", "video/x-ms-wvx");
                put(".x", "application/directx");
                put(".xaf", "x-world/x-vrml");
                put(".xaml", "application/xaml+xml");
                put(".xap", "application/x-silverlight-app");
                put(".xbap", "application/x-ms-xbap");
                put(".xbm", "image/x-xbitmap");
                put(".xdr", "text/plain");
                put(".xht", "application/xhtml+xml");
                put(".xhtml", "application/xhtml+xml");
                put(".xla", "application/vnd.ms-excel");
                put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
                put(".xlc", "application/vnd.ms-excel");
                put(".xld", "application/vnd.ms-excel");
                put(".xlk", "application/vnd.ms-excel");
                put(".xll", "application/vnd.ms-excel");
                put(".xlm", "application/vnd.ms-excel");
                put(".xls", "application/vnd.ms-excel");
                put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
                put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
                put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                put(".xlt", "application/vnd.ms-excel");
                put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
                put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
                put(".xlw", "application/vnd.ms-excel");
                put(".xml", "text/xml");
                put(".xmta", "application/xml");
                put(".xof", "x-world/x-vrml");
                put(".XOML", "text/plain");
                put(".xpm", "image/x-xpixmap");
                put(".xps", "application/vnd.ms-xpsdocument");
                put(".xrm-ms", "text/xml");
                put(".xsc", "application/xml");
                put(".xsd", "text/xml");
                put(".xsf", "text/xml");
                put(".xsl", "text/xml");
                put(".xslt", "text/xml");
                put(".xsn", "application/octet-stream");
                put(".xss", "application/xml");
                put(".xtp", "application/octet-stream");
                put(".xwd", "image/x-xwindowdump");
                put(".z", "application/x-compress");
                put(".zip", "application/x-zip-compressed");
            }
        };
    }

    public static String getMimeType(String extension) {
        if (extension == null) {
            return null;
        }

        if (!extension.startsWith(".")) {
            extension = "." + extension.toLowerCase(Locale.getDefault());
        }

        String mime = mimeTypes.get(extension);

        return mime != null ? mime : "application/octet-stream";
    }
}

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Set value to an entire column of a pandas dataframe

I had a similar issue before even with this approach df.loc[:,'industry'] = 'yyy', but once I refreshed the notebook, it ran well.

You may want to try refreshing the cells after you have df.loc[:,'industry'] = 'yyy'.

How to add an image to a JPanel?

I'm doing something very similar in a private project I'm working on. Thus far I've generated images up to 1024x1024 without any problems (except memory) and can display them very quickly and without any performance problems.

Overriding the paint method of JPanel subclass is overkill and requires more work than you need to do.

The way I do it is:

Class MapIcon implements Icon {...}

OR

Class MapIcon extends ImageIcon {...}

The code you use to generate the image will be in this class. I use a BufferedImage to draw onto then when the paintIcon() is called, use g.drawImvge(bufferedImage); This reduces the amount of flashing done while you generate your images, and you can thread it.

Next I extend JLabel:

Class MapLabel extends Scrollable, MouseMotionListener {...}

This is because I want to put my image on a scroll pane, I.e. display part of the image and have the user scroll around as needed.

So then I use a JScrollPane to hold the MapLabel, which contains only the MapIcon.

MapIcon map = new MapIcon (); 
MapLabel mapLabel = new MapLabel (map);
JScrollPane scrollPane = new JScrollPane();

scrollPane.getViewport ().add (mapLabel);

But for your scenario (just show the whole image every time). You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()).

How to convert a data frame column to numeric type?

Since (still) nobody got check-mark, I assume that you have some practical issue in mind, mostly because you haven't specified what type of vector you want to convert to numeric. I suggest that you should apply transform function in order to complete your task.

Now I'm about to demonstrate certain "conversion anomaly":

# create dummy data.frame
d <- data.frame(char = letters[1:5], 
                fake_char = as.character(1:5), 
                fac = factor(1:5), 
                char_fac = factor(letters[1:5]), 
                num = 1:5, stringsAsFactors = FALSE)

Let us have a glance at data.frame

> d
  char fake_char fac char_fac num
1    a         1   1        a   1
2    b         2   2        b   2
3    c         3   3        c   3
4    d         4   4        d   4
5    e         5   5        e   5

and let us run:

> sapply(d, mode)
       char   fake_char         fac    char_fac         num 
"character" "character"   "numeric"   "numeric"   "numeric" 
> sapply(d, class)
       char   fake_char         fac    char_fac         num 
"character" "character"    "factor"    "factor"   "integer" 

Now you probably ask yourself "Where's an anomaly?" Well, I've bumped into quite peculiar things in R, and this is not the most confounding thing, but it can confuse you, especially if you read this before rolling into bed.

Here goes: first two columns are character. I've deliberately called 2nd one fake_char. Spot the similarity of this character variable with one that Dirk created in his reply. It's actually a numerical vector converted to character. 3rd and 4th column are factor, and the last one is "purely" numeric.

If you utilize transform function, you can convert the fake_char into numeric, but not the char variable itself.

> transform(d, char = as.numeric(char))
  char fake_char fac char_fac num
1   NA         1   1        a   1
2   NA         2   2        b   2
3   NA         3   3        c   3
4   NA         4   4        d   4
5   NA         5   5        e   5
Warning message:
In eval(expr, envir, enclos) : NAs introduced by coercion

but if you do same thing on fake_char and char_fac, you'll be lucky, and get away with no NA's:

> transform(d, fake_char = as.numeric(fake_char), 
               char_fac = as.numeric(char_fac))

  char fake_char fac char_fac num
1    a         1   1        1   1
2    b         2   2        2   2
3    c         3   3        3   3
4    d         4   4        4   4
5    e         5   5        5   5

If you save transformed data.frame and check for mode and class, you'll get:

> D <- transform(d, fake_char = as.numeric(fake_char), 
                    char_fac = as.numeric(char_fac))

> sapply(D, mode)
       char   fake_char         fac    char_fac         num 
"character"   "numeric"   "numeric"   "numeric"   "numeric" 
> sapply(D, class)
       char   fake_char         fac    char_fac         num 
"character"   "numeric"    "factor"   "numeric"   "integer"

So, the conclusion is: Yes, you can convert character vector into a numeric one, but only if it's elements are "convertible" to numeric. If there's just one character element in vector, you'll get error when trying to convert that vector to numerical one.

And just to prove my point:

> err <- c(1, "b", 3, 4, "e")
> mode(err)
[1] "character"
> class(err)
[1] "character"
> char <- as.numeric(err)
Warning message:
NAs introduced by coercion 
> char
[1]  1 NA  3  4 NA

And now, just for fun (or practice), try to guess the output of these commands:

> fac <- as.factor(err)
> fac
???
> num <- as.numeric(fac)
> num
???

Kind regards to Patrick Burns! =)

phpmailer - The following SMTP Error: Data not accepted

set phpmailer to work in debug to see the "real" error behind the generic message 'SMTP Error: data not accepted' in our case the text in the message was triggering the smtp server spam filter.

  $email->SMTPDebug = true;

How to git reset --hard a subdirectory?

According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:

git checkout -- a

(where a is the directory you want to hard-reset). The original behavior can be accessed via

git checkout --ignore-skip-worktree-bits -- a

CodeIgniter - Correct way to link to another page in a view

I assume you are meaning "internally" within your application.

you can create your own <a> tag and insert a url in the href like this

<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>

OR you can use the URL helper this way to generate an <a> tag

anchor(uri segments, text, attributes)

So... to use it...

<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>

and that will generate

<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>

For the additional commented question

I would use my first example

so...

<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>

for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.

Opening database file from within SQLite command-line shell

The command within the Sqlite shell to open a database is .open

The syntax is,

sqlite> .open dbasename.db

If it is a new database that you would like to create and open, it is

sqlite> .open --new dbasename.db

If the database is existing in a different folder, the path has to be mentioned like this:

sqlite> .open D:/MainFolder/SubFolder/...database.db

In Windows Command shell, you should use '\' to represent a directory, but in SQLite directories are represented by '/'. If you still prefer to use the Windows notation, you should use an escape sequence for every '\'

how to get right offset of an element? - jQuery

Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:

var offset = $('#whatever').offset();

offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));

How to pass objects to functions in C++?

Do I need to pass pointers, references, or non-pointer and non-reference values?

This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.

The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &, is needed.

For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *.

How to display a date as iso 8601 format with PHP

Using the DateTime class available in PHP version 5.2 it would be done like this:

$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');

How can I check if string contains characters & whitespace, not just whitespace?

Just check the string against this regex:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}

What is the instanceof operator in JavaScript?

I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

What he didn't mention is this;

var color1 = String("green");
color1 instanceof String; // returns false

Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return name;
}

var test = new Test('test');
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.

var test = Test('test');
test.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns 'test'

Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

check if tun/tap enabled:

cat /dev/net/tun

if ok will see something :

cat: /dev/net/tun: File descriptor in bad state

Optimal way to concatenate/aggregate strings

SOLUTION

The definition of optimal can vary, but here's how to concatenate strings from different rows using regular Transact SQL, which should work fine in Azure.

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM dbo.SourceTable
),
Concatenated AS
(
    SELECT 
        ID, 
        CAST(Name AS nvarchar) AS FullName, 
        Name, 
        NameNumber, 
        NameCount 
    FROM Partitioned 
    WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, 
        CAST(C.FullName + ', ' + P.Name AS nvarchar), 
        P.Name, 
        P.NameNumber, 
        P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C 
                ON P.ID = C.ID 
                AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

EXPLANATION

The approach boils down to three steps:

  1. Number the rows using OVER and PARTITION grouping and ordering them as needed for the concatenation. The result is Partitioned CTE. We keep counts of rows in each partition to filter the results later.

  2. Using recursive CTE (Concatenated) iterate through the row numbers (NameNumber column) adding Name values to FullName column.

  3. Filter out all results but the ones with the highest NameNumber.

Please keep in mind that in order to make this query predictable one has to define both grouping (for example, in your scenario rows with the same ID are concatenated) and sorting (I assumed that you simply sort the string alphabetically before concatenation).

I've quickly tested the solution on SQL Server 2012 with the following data:

INSERT dbo.SourceTable (ID, Name)
VALUES 
(1, 'Matt'),
(1, 'Rocks'),
(2, 'Stylus'),
(3, 'Foo'),
(3, 'Bar'),
(3, 'Baz')

The query result:

ID          FullName
----------- ------------------------------
2           Stylus
3           Bar, Baz, Foo
1           Matt, Rocks

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

Get refresh token google api

Since March 2016, use prompt=consent to regenerate Google API refresh token.

As mentioned in https://github.com/googleapis/oauth2client/issues/453,

approval_prompt=force has been replaced with prompt=none|consent|select_account

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

Regular expression to stop at first match

Because you are using quantified subpattern and as descried in Perl Doc,

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?" . Note that the meanings don't change, just the "greediness":

*?        //Match 0 or more times, not greedily (minimum matches)
+?        //Match 1 or more times, not greedily

Thus, to allow your quantified pattern to make minimum match, follow it by ? :

/location="(.*?)"/

Getting a random value from a JavaScript array

Here is an example of how to do it:

$scope.ctx.skills = data.result.skills;
    $scope.praiseTextArray = [
    "Hooray",
    "You\'re ready to move to a new skill", 
    "Yahoo! You completed a problem", 
    "You\'re doing great",  
    "You succeeded", 
    "That was a brave effort trying new problems", 
    "Your brain was working hard",
    "All your hard work is paying off",
    "Very nice job!, Let\'s see what you can do next",
    "Well done",
    "That was excellent work",
    "Awesome job",
    "You must feel good about doing such a great job",
    "Right on",
    "Great thinking",
    "Wonderful work",
    "You were right on top of that one",
    "Beautiful job",
    "Way to go",
    "Sensational effort"
  ];

  $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];

Force uninstall of Visual Studio

I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:

D:\vs_ultimate.exe /uninstall /force

Where D: is the location of your installation media (mounted iso, etc).

You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.

EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.

http://blogs.msdn.com/b/heaths/archive/2015/07/17/removing-visual-studio-components-left-behind-after-an-uninstall.aspx

Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.

Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.

Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.

Good luck!

How to resize array in C++?

Raw arrays aren't resizable in C++.

You should be using something like a Vector class which does allow resizing..

std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).

get data from mysql database to use in javascript

Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

$result = mysql_query("SELECT field_name, field_value
                       FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);

If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

<!DOCTYPE html>
<html>
  <head>
    <title>That's about it</title>
  </head>
  <body>
    <form>
      <input type="text" id="field1" />
      <input type="text" id="field2" />
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script>
    $.getJSON('data.php', function(data) {
      $.each(data, function(fieldName, fieldValue) {
        $("#" + fieldName).val(fieldValue);
      });
    });
  </script>
</html>

That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.

Swift presentViewController

Try this:

let vc = ViewController() //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)

With Swift3:

self.present(vc, animated: true, completion: nil)

Spring @PropertySource using YAML

I needed to read some properties into my code and this works with spring-boot 1.3.0.RELEASE

@Autowired
private ConfigurableListableBeanFactory beanFactory;

// access a properties.yml file like properties
@Bean
public PropertySource properties() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource("properties.yml"));
    propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
    // properties need to be processed by beanfactory to be accessible after
    propertySourcesPlaceholderConfigurer.postProcessBeanFactory(beanFactory);
    return propertySourcesPlaceholderConfigurer.getAppliedPropertySources().get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME);
}

Jenkins - passing variables between jobs?

I figured it out!

With almost 2 hours worth of trial and error, i figured it out.

This WORKS and is what you do to pass variables to remote job:

    def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2=${env.param2}")

Use \n to separate two parameters, no spaces..

As opposed to parameters: '''someparams'''

we use paramters: "someparams"

the " ... " is what gets us the values of the desired variables. (These are double quotes, not two single quotes)

the ''' ... ''' or ' ... ' will not get us those values. (Three single quotes or just single quotes)

All parameters here are defined in environment{} block at the start of the pipeline and are modified in stages>steps>scripts wherever necessary.

I also tested and found that when you use " ... " you cannot use something like ''' ... "..." ''' or "... '..'..." or any combination of it...

The catch here is that when you are using "..." in parameters section, you cannot pass a string parameter; for example This WILL NOT WORK:

    def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2='param2'")

if you want to pass something like the one above, you will need to set an environment variable param2='param2' and then use ${env.param2} in the parameters section of remote trigger plugin step

How does delete[] know it's an array?

One question that the answers given so far don't seem to address: if the runtime libraries (not the OS, really) can keep track of the number of things in the array, then why do we need the delete[] syntax at all? Why can't a single delete form be used to handle all deletes?

The answer to this goes back to C++'s roots as a C-compatible language (which it no longer really strives to be.) Stroustrup's philosophy was that the programmer should not have to pay for any features that they aren't using. If they're not using arrays, then they should not have to carry the cost of object arrays for every allocated chunk of memory.

That is, if your code simply does

Foo* foo = new Foo;

then the memory space that's allocated for foo shouldn't include any extra overhead that would be needed to support arrays of Foo.

Since only array allocations are set up to carry the extra array size information, you then need to tell the runtime libraries to look for that information when you delete the objects. That's why we need to use

delete[] bar;

instead of just

delete bar;

if bar is a pointer to an array.

For most of us (myself included), that fussiness about a few extra bytes of memory seems quaint these days. But there are still some situations where saving a few bytes (from what could be a very high number of memory blocks) can be important.

Find where python is installed (if it isn't default dir)

On windows search python,then right click and click on "Open file location".That's how I did

C++ passing an array pointer as a function argument

I'm guessing this will help.

When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type: int x[] or int x[a] . Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.

How to exit a 'git status' list in a terminal?

q or SHIFT+q will do the trick. This will get you out of many extensive page scrolling sessions like git status, git show HEAD, git diff etc. This will not exit your window or end your session.

How to lazy load images in ListView in Android

I made a simple demo of a lazy list (located at GitHub) with images.

Basic Usage

ImageLoader imageLoader=new ImageLoader(context); ...
imageLoader.DisplayImage(url, imageView); 

Don't forget to add the following permissions to your AndroidManifest.xml:

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Please

create only one instance of ImageLoader and reuse it all around your application. This way image caching will be much more efficient.

It may be helpful to somebody. It downloads images in the background thread. Images are being cached on an SD card and in memory. The cache implementation is very simple and is just enough for the demo. I decode images with inSampleSize to reduce memory consumption. I also try to handle recycled views correctly.

Alt text

Removing the title text of an iOS UIBarButtonItem

SWIFT 3

navigationController?.navigationBar.topItem?.title = ""

Javascript close alert box

The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.

Running Tensorflow in Jupyter Notebook

I believe a short video showing all the details if you have Anaconda is the following for mac (it is very similar to windows users as well) just open Anaconda navigator and everything is just the same (almost!)

https://www.youtube.com/watch?v=gDzAm25CORk

Then go to jupyter notebook and code

!pip install tensorflow

Then

import tensorflow as tf

It work for me! :)

How to Resize a Bitmap in Android?

While the previous answers do scale the image and take care of the aspect ratio, the resampling itself should be done so that there is no aliasing. Taking care of scale is a matter of fixing arguments correctly. There are many comments about the quality of the output images from standard scaling call. to maintain quality of the image one should use the standard call:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);

with the last argument set to true because it will do the bilinear filtering for resampling to prevent aliasing. Read more about aliasing here: https://en.wikipedia.org/wiki/Aliasing

From android documentation:

https://developer.android.com/reference/android/graphics/Bitmap#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)


public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)

filter : boolean, Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.

Uncaught TypeError: Cannot read property 'appendChild' of null

add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

is vs typeof

I did some benchmarking where they do the same - sealed types.

var c1 = "";
var c2 = typeof(string);
object oc1 = c1;
object oc2 = c2;

var s1 = 0;
var s2 = '.';
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(string); // ~60ms
    b = c1 is string; // ~60ms

    b = c2.GetType() == typeof(string); // ~60ms
    b = c2 is string; // ~50ms

    b = oc1.GetType() == typeof(string); // ~60ms
    b = oc1 is string; // ~68ms

    b = oc2.GetType() == typeof(string); // ~60ms
    b = oc2 is string; // ~64ms


    b = s1.GetType() == typeof(int); // ~130ms
    b = s1 is int; // ~50ms

    b = s2.GetType() == typeof(int); // ~140ms
    b = s2 is int; // ~50ms

    b = os1.GetType() == typeof(int); // ~60ms
    b = os1 is int; // ~74ms

    b = os2.GetType() == typeof(int); // ~60ms
    b = os2 is int; // ~68ms


    b = GetType1<string, string>(c1); // ~178ms
    b = GetType2<string, string>(c1); // ~94ms
    b = Is<string, string>(c1); // ~70ms

    b = GetType1<string, Type>(c2); // ~178ms
    b = GetType2<string, Type>(c2); // ~96ms
    b = Is<string, Type>(c2); // ~65ms

    b = GetType1<string, object>(oc1); // ~190ms
    b = Is<string, object>(oc1); // ~69ms

    b = GetType1<string, object>(oc2); // ~180ms
    b = Is<string, object>(oc2); // ~64ms


    b = GetType1<int, int>(s1); // ~230ms
    b = GetType2<int, int>(s1); // ~75ms
    b = Is<int, int>(s1); // ~136ms

    b = GetType1<int, char>(s2); // ~238ms
    b = GetType2<int, char>(s2); // ~69ms
    b = Is<int, char>(s2); // ~142ms

    b = GetType1<int, object>(os1); // ~178ms
    b = Is<int, object>(os1); // ~69ms

    b = GetType1<int, object>(os2); // ~178ms
    b = Is<int, object>(os2); // ~69ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

The generic functions to test for generic types:

static bool GetType1<S, T>(T t)
{
    return t.GetType() == typeof(S);
}
static bool GetType2<S, T>(T t)
{
    return typeof(T) == typeof(S);
}
static bool Is<S, T>(T t)
{
    return t is S;
}

I tried for custom types as well and the results were consistent:

var c1 = new Class1();
var c2 = new Class2();
object oc1 = c1;
object oc2 = c2;

var s1 = new Struct1();
var s2 = new Struct2();
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(Class1); // ~60ms
    b = c1 is Class1; // ~60ms

    b = c2.GetType() == typeof(Class1); // ~60ms
    b = c2 is Class1; // ~55ms

    b = oc1.GetType() == typeof(Class1); // ~60ms
    b = oc1 is Class1; // ~68ms

    b = oc2.GetType() == typeof(Class1); // ~60ms
    b = oc2 is Class1; // ~68ms


    b = s1.GetType() == typeof(Struct1); // ~150ms
    b = s1 is Struct1; // ~50ms

    b = s2.GetType() == typeof(Struct1); // ~150ms
    b = s2 is Struct1; // ~50ms

    b = os1.GetType() == typeof(Struct1); // ~60ms
    b = os1 is Struct1; // ~64ms

    b = os2.GetType() == typeof(Struct1); // ~60ms
    b = os2 is Struct1; // ~64ms


    b = GetType1<Class1, Class1>(c1); // ~178ms
    b = GetType2<Class1, Class1>(c1); // ~98ms
    b = Is<Class1, Class1>(c1); // ~78ms

    b = GetType1<Class1, Class2>(c2); // ~178ms
    b = GetType2<Class1, Class2>(c2); // ~96ms
    b = Is<Class1, Class2>(c2); // ~69ms

    b = GetType1<Class1, object>(oc1); // ~178ms
    b = Is<Class1, object>(oc1); // ~69ms

    b = GetType1<Class1, object>(oc2); // ~178ms
    b = Is<Class1, object>(oc2); // ~69ms


    b = GetType1<Struct1, Struct1>(s1); // ~272ms
    b = GetType2<Struct1, Struct1>(s1); // ~140ms
    b = Is<Struct1, Struct1>(s1); // ~163ms

    b = GetType1<Struct1, Struct2>(s2); // ~272ms
    b = GetType2<Struct1, Struct2>(s2); // ~140ms
    b = Is<Struct1, Struct2>(s2); // ~163ms

    b = GetType1<Struct1, object>(os1); // ~178ms
    b = Is<Struct1, object>(os1); // ~64ms

    b = GetType1<Struct1, object>(os2); // ~178ms
    b = Is<Struct1, object>(os2); // ~64ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

And the types:

sealed class Class1 { }
sealed class Class2 { }
struct Struct1 { }
struct Struct2 { }

Inference:

  1. Calling GetType on structs is slower. GetType is defined on object class which can't be overridden in sub types and thus structs need to be boxed to be called GetType.

  2. On an object instance, GetType is faster, but very marginally.

  3. On generic type, if T is class, then is is much faster. If T is struct, then is is much faster than GetType but typeof(T) is much faster than both. In cases of T being class, typeof(T) is not reliable since its different from actual underlying type t.GetType.

In short, if you have an object instance, use GetType. If you have a generic class type, use is. If you have a generic struct type, use typeof(T). If you are unsure if generic type is reference type or value type, use is. If you want to be consistent with one style always (for sealed types), use is..

For homebrew mysql installs, where's my.cnf?

For MacOS (High Sierra), MySQL that has been installed with home brew.

Increasing the global variables from mysql environment was not successful. So in that case creating of ~/.my.cnf is the safest option. Adding variables with [mysqld] will include the changes (Note: if you change with [mysql] , the change might not work).

<~/.my.cnf> [mysqld] connect_timeout = 43200 max_allowed_packet = 2048M net_buffer_length = 512M

Restart the mysql server. and check the variables. y

sql> SELECT @@max_allowed_packet; +----------------------+ | @@max_allowed_packet | +----------------------+ | 1073741824 | +----------------------+

1 row in set (0.00 sec)

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

How can I check whether an array is null / empty?

I am from .net background. However, java/c# are more/less same.

If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.

It will be null, when you don't new it up.
e.g.

int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
   System.out.println("yes, it is null. Please new it up");
}

PHP Error: Cannot use object of type stdClass as array (array and object issues)

There might two issues

1) $blogs may be a stdObject

or

2) The properties of the array might be the stdObject

Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this

$blog->id;
$blog->content;
$blog->title;

How to set selected item of Spinner by value, not by position?

very simple just use getSelectedItem();

eg :

ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
        type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mainType.setAdapter(type);

String group=mainType.getSelectedItem().toString();

the above method returns an string value

in the above the R.array.admin_type is an string resource file in values

just create an .xml file in values>>strings

Auto Generate Database Diagram MySQL

In MySql Workbench (6.0) its possible generate one diagram based on tables created. For that you should access to the tools bar, press Model and forward Create Diagram from Catalog Objects and done!

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Different connections pools have different configs.

For example Tomcat (default) expects:

spring.datasource.ourdb.url=...

and HikariCP will be happy with:

spring.datasource.ourdb.jdbc-url=...

We can satisfy both without boilerplate configuration:

spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}

There is no property to define connection pool provider.

Take a look at source DataSourceBuilder.java

If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).

... so, we can easily replace connection pool provider using this maven configuration (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>       

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

jQuery prevent change for select

Implement custom readonly like eventHandler

<select id='country' data-changeable=false>
  <option selected value="INDIA">India</option>
  <option value="USA">United States</option>
  <option value="UK">United Kingdom</option>
</select>

<script>
    var lastSelected = $("#country option:selected");

    $("#country").on("change", function() {
       if(!$(this).data(changeable)) {
            lastSelected.attr("selected", true);              
       }        
    });

    $("#country").on("click", function() {
       lastSelected = $("#country option:selected");
    });
</script>

Demo : https://jsfiddle.net/0mvajuay/8/

Display TIFF image in all web browser

Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you

How to create a Date in SQL Server given the Day, Month and Year as Integers

In SQL Server 2012+, you can use DATEFROMPARTS():

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

In earlier versions, one method is to create and convert a string.

There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.

A six- or eight-digit string is always interpreted as ymd. The month and day must always be two digits.

https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql

So a string in the format 'yyyymmdd' will always be properly interpreted.

(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)

While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).

The "yyyymmdd" format is style 112, so your conversion looks like this:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

And it results in:

2016-10-25

Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):

DECLARE @Year int = 2016, @Month int = 10, @Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),104);

Also still results in:

2016-10-25

Other formats are not as robust. For example this:

SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;

Results in:

0

As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:

DECLARE @Year int = 2016, @Month int = 0, @Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Also yields:

2016-10-25

DATEFROMPARTS protects you from invalid inputs. This:

DECLARE @Year int = 2016, @Month int = 10, @Day int = 32;
SELECT DATEFROMPARTS (@Year, @Month, @Day);

Yields:

Msg 289, Level 16, State 1, Line 2 Cannot construct data type date, some of the arguments have values which are not valid.

Also beware that this method does not work for dates prior to 1000-01-01. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),112);

Yields:

Msg 241, Level 16, State 1, Line 2 Conversion failed when converting date and/or time from character string.

That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:

DECLARE @Year int = 900, @Month int = 1, @Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(@Year*10000 + @Month*100 + @Day)),8),112);

Results in:

0900-01-01

There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".

(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

increase the java heap size permanently?

For Windows users, you can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there. The JVM should be able to grab the virtual machine options from _JAVA_OPTIONS.

How to Refresh a Component in Angular

After some research and modifying my code as below, the script worked for me. I just added the condition:

this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this.router.navigate(['Your actualComponent']);
}); 

Get JSF managed bean by name in any Servlet related class

I use the following method:

public static <T> T getBean(final String beanName, final Class<T> clazz) {
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
}

This allows me to get the returned object in a typed manner.

Adding a slide effect to bootstrap dropdown

I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:

Here is the result: Bootply example

Javascript/Jquery:

$(function(){
    // ADD SLIDEDOWN ANIMATION TO DROPDOWN //
    $('.dropdown').on('show.bs.dropdown', function(e){
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
    });

    // ADD SLIDEUP ANIMATION TO DROPDOWN //
    $('.dropdown').on('hide.bs.dropdown', function(e){
        e.preventDefault();
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
            //On Complete, we reset all active dropdown classes and attributes
            //This fixes the visual bug associated with the open class being removed too fast
            $('.dropdown').removeClass('show');
            $('.dropdown-menu').removeClass('show');
            $('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
        });
    });
});

Receiving JSON data back from HTTP request

I think the shortest way is:

var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
    FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();

How to show grep result with complete path or file name

I fall here when I was looking exactly for the same problem and maybe it can help other.

I think the real solution is:

cat *.log | grep -H somethingtosearch

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

How to enable ASP classic in IIS7.5

I found some detailed instructions here: http://digitallibraryworld.com/?p=6

The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).

Add a script map using the following setting:

Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASP

The executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location: C:\Windows\SysWOW64\inetsrv\asp.dll.

Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!

How to get Month Name from Calendar?

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.

This is what you get, if you use getDisplayName from the Calendar or DateFormatSymbols for January:

?????? (which is correct for a complete date string: "10 ??????, 2014")

but in case of a stand-alone month name you would expect:

??????

How to call a function in shell Scripting?

Summary:

  • Define functions before using them.
  • Once defined, treat them as commands.

Consider this script, called funcdemo:

#!/bin/bash

[ $# = 0 ] && exhort "write nastygram"

exhort(){
    echo "Please, please do not forget to $*"
}

[ $# != 0 ] && exhort "write begging letter"

In use:

$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$

Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.

Parse JSON response using jQuery

Original question was to parse a list of topics, however starting with the original example to have a function return a single value may also useful. To that end, here is an example of (one way) to do that:

<script type='text/javascript'>
    function getSingleValueUsingJQuery() {
      var value = "";
      var url = "rest/endpointName/" + document.getElementById('someJSPFieldName').value;
      jQuery.ajax({
        type: 'GET',
        url: url,
        async: false,
        contentType: "application/json",
        dataType: 'json',
        success: function(json) {
          console.log(json.value);   // needs to match the payload (i.e. json must have {value: "foo"}
          value = json.value;
        },
        error: function(e) {
          console.log("jQuery error message = "+e.message);
        }
      });
      return value;
    }
    </script>
    

Representing null in JSON

null is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.

There is only one way to represent null in JSON. Per the specs (RFC 4627 and json.org):

2.1.  Values

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

  false null true

enter image description here

JavaScript Array splice vs slice

splice() changes the original array whereas slice() doesn't but both of them returns array object.

See the examples below:

var array=[1,2,3,4,5];
console.log(array.splice(2));

This will return [3,4,5]. The original array is affected resulting in array being [1,2].

var array=[1,2,3,4,5]
console.log(array.slice(2));

This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].

Below is simple fiddle which confirms this:

_x000D_
_x000D_
//splice_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
_x000D_
//slice_x000D_
var array2=[1,2,3,4,5]_x000D_
console.log(array2.slice(2));_x000D_
_x000D_
_x000D_
console.log("----after-----");_x000D_
console.log(array);_x000D_
console.log(array2);
_x000D_
_x000D_
_x000D_

How do I get the App version and build number using Swift?

EDIT

Updated for Swift 4.2

let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String

EDIT

As pointed out by @azdev on the new version of Xcode you will get a compile error for trying my previous solution, to solve this just edit it as suggested to unwrap the bundle dictionary using a !

let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"]

End Edit

Just use the same logic than in Objective-C but with some small changes

//First get the nsObject by defining as an optional anyObject
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary["CFBundleShortVersionString"]

//Then just cast the object as a String, but be careful, you may want to double check for nil
let version = nsObject as! String

I hope this helps you out.

David

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

Perform an action in every sub-directory using Bash

You could try:

#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/

for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
  cd "$f"
  <your job here>
done

or similar...

Explanation:

find . -maxdepth 1 -mindepth 1 -type d : Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .)

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Generally Server JDK version will be lower than the deployed application (built with higher jdk version)

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

The compiler will start doing very clever things with optimisations turned on. The debugger will show the code jumping forward and backwards alot due to the optimized way variables are stored in registers. This is probably the reason why you can't set your variable (or in some cases see its value) as it has been cleverly distributed between registers for speed, rather than having a direct memory location that the debugger can access.

Compile without optimisations?

How do I upload a file to an SFTP server in C# (.NET)?

There is no solution for this within the .net framework.

http://www.eldos.com/sbb/sftpcompare.php outlines a list of un-free options.

your best free bet is to extend SSH using Granados. http://www.routrek.co.jp/en/product/varaterm/granados.html

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

How to check the multiple permission at single request in Android M?

First initialize permission request code

public  static final int PERMISSIONS_MULTIPLE_REQUEST = 123;

Check android version

 private void checkAndroidVersion() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkPermission();

    } else {
        // write your logic here
    }

}

check multiple permission code

 private void checkPermission() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
            .checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale
                (getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                ActivityCompat.shouldShowRequestPermissionRationale
                        (getActivity(), Manifest.permission.CAMERA)) {

      Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Please Grant Permissions to upload profile photo",
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            requestPermissions(
                                    new String[]{Manifest.permission
                                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                    PERMISSIONS_MULTIPLE_REQUEST);
                        }
                    }).show();
        } else {
            requestPermissions(
                    new String[]{Manifest.permission
                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    PERMISSIONS_MULTIPLE_REQUEST);
        }
    } else {
        // write your logic code if permission already granted
    }
}

call back method after grant permission by user

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_MULTIPLE_REQUEST:
            if (grantResults.length > 0) {
               boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
               boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                if(cameraPermission && readExternalFile)
                {
                    // write your logic here 
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                        "Please Grant Permissions to upload profile photo",
                        Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermissions(
                                        new String[]{Manifest.permission
                                                .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                        PERMISSIONS_MULTIPLE_REQUEST);
                            }
                        }).show();
                }
           }
           break;
    }
}

Restart container within pod

There was an issue in coredns pod, I deleted such pod by

kubectl delete pod -n=kube-system coredns-fb8b8dccf-8ggcf

Its pod will restart automatically.

redirect COPY of stdout to log file from within bash script itself

Solution for busybox, macOS bash, and non-bash shells

The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt) syntax. It also does not do exec >$PIPE properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.

Hopefully this would be useful to someone else who doesn't have bash.

Also, for anyone using a named pipe, it is safe to rm $PIPE, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.

Note the use of $* is not necessarily safe.

#!/bin/sh

if [ "$SELF_LOGGING" != "1" ]
then
    # The parent process will enter this branch and set up logging

    # Create a named piped for logging the child's output
    PIPE=tmp.fifo
    mkfifo $PIPE

    # Launch the child process with stdout redirected to the named pipe
    SELF_LOGGING=1 sh $0 $* >$PIPE &

    # Save PID of child process
    PID=$!

    # Launch tee in a separate process
    tee logfile <$PIPE &

    # Unlink $PIPE because the parent process no longer needs it
    rm $PIPE    

    # Wait for child process, which is running the rest of this script
    wait $PID

    # Return the error code from the child process
    exit $?
fi

# The rest of the script goes here

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

How can I list all foreign keys referencing a given table in SQL Server?

This gives you:

  • The FK itself itself
  • Schema that the FK belongs to
  • The "referencing table" or the table that has the FK
  • The "referencing column" or the column inside referencing table that points to the FK
  • The "referenced table" or the table that has the key column that your FK is pointing to
  • The "referenced column" or the column that is the key that your FK is pointing to

Code below:

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id

jquery $(this).id return Undefined

Another option (just so you've seen it):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});

HTH.

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

The problem with the answer with the most votes is it doesn't explain the reasoning for the solution.

For the lines Require ip 127.0.0.1, you should instead add the ip address of the host that plans to access phpMyAdmin from a browser. For example Require ip 192.168.0.100. The Require ip 127.0.0.1 allows localhost access to phpMyAdmin.

Restart apache (httpd) after making changes. I would suggest testing on localhost, or using command line tools like curl to very a http GET works, and there is no other configuration issue.

How do I clear my local working directory in Git?

To reset a specific file to the last-committed state (to discard uncommitted changes in a specific file):

git checkout thefiletoreset.txt

This is mentioned in the git status output:

(use "git checkout -- <file>..." to discard changes in working directory)

To reset the entire repository to the last committed state:

git reset --hard

To remove untracked files, I usually just delete all files in the working copy (but not the .git/ folder!), then do git reset --hard which leaves it with only committed files.

A better way is to use git clean (warning: using the -x flag as below will cause Git to delete ignored files):

git clean -d -x -f

will remove untracked files, including directories (-d) and files ignored by git (-x). Replace the -f argument with -n to perform a dry-run or -i for interactive mode, and it will tell you what will be removed.

Relevant links:

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

Check this:

foreach (Control x in this.Controls)
{
    if (x is TextBox)
    {
        x.Text = "";
    }
}

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

How to pretty-print a numpy.array without scientific notation and with given precision?

I find that the usual float format {:9.5f} works properly -- suppressing small-value e-notations -- when displaying a list or an array using a loop. But that format sometimes fails to suppress its e-notation when a formatter has several items in a single print statement. For example:

import numpy as np
np.set_printoptions(suppress=True)
a3 = 4E-3
a4 = 4E-4
a5 = 4E-5
a6 = 4E-6
a7 = 4E-7
a8 = 4E-8
#--first, display separate numbers-----------
print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
#---second, display a list using a loop----------
myList = [a3,a4,a5,a6,a7,a8]
print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
for x in myList: 
    print('{:9.5f}'.format(x), end='')
print()
#---third, display a numpy array using a loop------------
myArray = np.array(myList)
print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
for x in myArray:
    print('{:9.5f}'.format(x), end='')
print()

My results show the bug in cases 4, 5, and 6:

Case 3:  a3, a4, a5:               0.00400  0.00040  0.00004
Case 4:  a3, a4, a5, a6:           0.00400  0.00040  0.00004    4e-06
Case 5:  a3, a4, a5, a6, a7:       0.00400  0.00040  0.00004    4e-06  0.00000
Case 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000    4e-07  0.00000
List 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
Array 6: a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000

I have no explanation for this, and therefore I always use a loop for floating output of multiple values.

How can I compare time in SQL Server?

I am assuming your startHour column and @startHour variable are both DATETIME; In that case, you should be converting to a string:

SELECT timeEvent
FROM tbEvents
WHERE convert(VARCHAR(8), startHour, 8) >= convert(VARCHAR(8), @startHour, 8)

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

These steps are working on CentOS 6.5 so they should work on CentOS 7 too:

(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)

  1. yum remove mariadb mariadb-server
  2. rm -rf /var/lib/mysql If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysql
  3. rm /etc/my.cnf the file might have already been deleted at step 1
  4. Optional step: rm ~/.my.cnf
  5. yum install mariadb mariadb-server

[EDIT] - Update for MariaDB 10.1 on CentOS 7

The steps above worked for CentOS 6.5 and MariaDB 10.

I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.

Step 1 would become:

yum remove MariaDB-server MariaDB-client

Step 5 would become:

yum install MariaDB-server MariaDB-client

The other steps remain the same.

jQuery AJAX submit form

There are a few things you need to bear in mind.

1. There are several ways to submit a form

  • using the submit button
  • by pressing enter
  • by triggering a submit event in JavaScript
  • possibly more depending on the device or future device.

We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.

2. Hijax

The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.

We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.

3. Unobtrusive JavaScript

Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.

Speed

We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.

Code

Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:

$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});

You can manually trigger a form submission whenever you like via JavaScript using something like:

$(function() {
  $('form.my_form').trigger('submit');
});

Edit:

I recently had to do this and ended up writing a plugin.

(function($) {
  $.fn.autosubmit = function() {
    this.submit(function(event) {
      event.preventDefault();
      var form = $(this);
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize()
      }).done(function(data) {
        // Optionally alert the user of success here...
      }).fail(function(data) {
        // Optionally alert the user of an error here...
      });
    });
    return this;
  }
})(jQuery)

Add a data-autosubmit attribute to your form tag and you can then do this:

HTML

<form action="/blah" method="post" data-autosubmit>
  <!-- Form goes here -->
</form>

JS

$(function() {
  $('form[data-autosubmit]').autosubmit();
});

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

Can I add background color only for padding?

the answers said all the possible solutions

I have another one with BOX-SHADOW

here it is JSFIDDLE

and the code

nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
    box-shadow: 0 0 0 10px blue inset;
}

it also support in IE9, so It's better than gradient solution, add proper prefixes for more support

IE8 dont support it, what a shame !

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

Using %f with strftime() in Python to get microseconds

You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

What is monkey patching?

First: monkey patching is an evil hack (in my opinion).

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.

How to generate a unique hash code for string input in android...?

You can use this code for generating has code for a given string.

int hash = 7;
for (int i = 0; i < strlen; i++) {
    hash = hash*31 + charAt(i);
}

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

On npm install: Unhandled rejection Error: EACCES: permission denied

just create folders _cache/tmp under .npm manually at location /Users/marknorgate/.npm/_cacache/tmp and run your command with administrator access

How to lock orientation of one view controller to portrait mode only in Swift

bmjohns -> You are my life saviour. That is the only working solution (With the AppUtility struct)

I've created this class:

class Helper{
    struct AppUtility {

        static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

            if let delegate = UIApplication.shared.delegate as? AppDelegate {
                delegate.orientationLock = orientation
            }
        }

        /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

            self.lockOrientation(orientation)

            UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        }

    }
}

and followed your instructions, and everything works perfectly for Swift 3 -> xcode version 8.2.1

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional

Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

How would you implement an LRU cache in Java?

LRU Cache can be implemented using a ConcurrentLinkedQueue and a ConcurrentHashMap which can be used in multithreading scenario as well. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. When an element exists in the Map, we can remove it from the LinkedQueue and insert it at the tail.

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class LRUCache<K,V> {
  private ConcurrentHashMap<K,V> map;
  private ConcurrentLinkedQueue<K> queue;
  private final int size; 

  public LRUCache(int size) {
    this.size = size;
    map = new ConcurrentHashMap<K,V>(size);
    queue = new ConcurrentLinkedQueue<K>();
  }

  public V get(K key) {
    //Recently accessed, hence move it to the tail
    queue.remove(key);
    queue.add(key);
    return map.get(key);
  }

  public void put(K key, V value) {
    //ConcurrentHashMap doesn't allow null key or values
    if(key == null || value == null) throw new NullPointerException();
    if(map.containsKey(key) {
      queue.remove(key);
    }
    if(queue.size() >= size) {
      K lruKey = queue.poll();
      if(lruKey != null) {
        map.remove(lruKey);
      }
    }
    queue.add(key);
    map.put(key,value);
  }

}

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

How do I tell if a regular file does not exist in Bash?

You can do this:

[[ ! -f "$FILE" ]] && echo "File doesn't exist"

or

if [[ ! -f "$FILE" ]]; then
    echo "File doesn't exist"
fi

If you want to check for file and folder both, then use -e option instead of -f. -e returns true for regular files, directories, socket, character special files, block special files etc.

Java - No enclosing instance of type Foo is accessible

Declare the INNER class Thing as a static and it will work with no issues.

I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

1- To declare the inner class Dog as static. Or

2- To move the inner class Dog to a new class by itself.

Here is the Example:

public class ReturnDemo {

public static void main(String[] args) {
    
    int z = ReturnDemo.calculate(10, 12);
    System.out.println("z = " + z);
    
    ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
    System.out.println( dog.getDog());
}


public static int calculate (int x, int y) {
    return x + y;
}

public void print( ) {
    System.out.println("void method");
    return;
}

public String getString() {
    return "Retrun String type value";
}


static class Dog {
    
private String breed;
private String name;

public Dog(String breed, String name) {
    super();
    this.breed = breed;
    this.name = name;
}

public Dog getDog() {
    // return Dog type;
    return this;
    
}

public String toString() {
    return "breed" + breed.concat("name: " + name);
}
}

}

How to search JSON data in MySQL?

For Mysql8->

Query:

SELECT properties, properties->"$.price" FROM book where isbn='978-9730228236' and  JSON_EXTRACT(properties, "$.price") > 400;

Data:

mysql> select * from book\G;
*************************** 1. row ***************************
id: 1
isbn: 978-9730228236
properties: {"price": 44.99, "title": "High-Performance Java Persistence", "author": "Vlad Mihalcea", "publisher": "Amazon"}
1 row in set (0.00 sec)

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

The code on Scene delegate in Swift UI

Content view background-color

window.rootViewController?.view.backgroundColor = .lightGray

How to use Python to execute a cURL command?

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

its python implementation be like

import requests

headers = {
    'Content-Type': 'application/json',
}

params = (
    ('key', 'mykeyhere'),
)

data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)

check this link, it will help convert cURl command to python,php and nodejs

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

For those who are getting the "Unable to resolve dependencies" error:
Toggle "Offline Mode" off
('View'->Tool Windows->Gradle)

gradle window

How to make the Facebook Like Box responsive?

NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using * should be more future-proof.

Wrap the Like box with a div:

<div id="likebox-wrapper">
    <iframe src="..."></iframe> <!-- likebox code -->
</div>

and add this to your css file:

#likebox-wrapper * {
   width: 100% !important;
}

Is there a .NET/C# wrapper for SQLite?

There's also now this option: http://code.google.com/p/csharp-sqlite/ - a complete port of SQLite to C#.

Calling a Javascript Function from Console

This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here

Postgres DB Size Command

Start pgAdmin, connect to the server, click on the database name, and select the statistics tab. You will see the size of the database at the bottom of the list.

Then if you click on another database, it stays on the statistics tab so you can easily see many database sizes without much effort. If you open the table list, it shows all tables and their sizes.

How to style dt and dd so they are on the same line?

If you use Bootstrap 3 (or earlier)...

<dl class="dl-horizontal">
    <dt>Label:</dt>
    <dd>
      Description of planet
    </dd>
    <dt>Label2:</dt>
    <dd>
      Description of planet
    </dd>
</dl>

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    }
    100% {
      background-color: #AD310B;
    }
  }
}

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;
}

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.