Programs & Examples On #Stage

In case of ActionScript terminology, stage is used as a parent Display Object of all assets like images, text, videos, swf, etc. those are placed on this stage. These assets are not displayed until they are added to stage.

JavaFX Application Icon

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png")));

If your icon.png is in resources dir and remember to put a '/' before otherwise it will not work

JavaFX: How to get stage from controller during initialization?

You can get the instance of the controller from the FXMLLoader after initialization via getController(), but you need to instantiate an FXMLLoader instead of using the static methods then.

I'd pass the stage after calling load() directly to the controller afterwards:

FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do

JavaFX Location is not set error message

I tried a fast and simple thing:

I have two packages -> app.gui and app.login

In my login class I use the mainview.fxml from app.gui so I did this in the login.fxml

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../gui/MainView.fxml"));

And it works :)

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Rename multiple files in cmd

Try this Bulk Rename Utility It works well. Maybe not reinvent the wheel. If you don't necessary need a script this is a good way to go.

SQL 'like' vs '=' performance

First things first ,

they are not always equal

    select 'Hello' from dual where 'Hello  ' like 'Hello';

    select 'Hello' from dual where 'Hello  ' =  'Hello';

when things are not always equal , talking about their performance isn't that relevant.

If you are working on strings and only char variables , then you can talk about performance . But don't use like and "=" as being generally interchangeable .

As you would have seen in many posts ( above and other questions) , in cases when they are equal the performance of like is slower owing to pattern matching (collation)

SELECT query with CASE condition and SUM()

select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

Cheers -

Failure during conversion to COFF: file invalid or corrupt

I had this issue and I solved it with this thread

disable incremental linking, by going to

    Project Properties 
       -> Configuration Properties 
           -> Linker (General) 
              -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"

JQuery get data from JSON array

You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text tries to point to a string. Both groups and items are arrays.

Verbose version:

$.getJSON(url, function (data) {

    // Iterate the groups first.
    $.each(data.response.venue.tips.groups, function (index, value) {

        // Get the items
        var items = this.items; // Here 'this' points to a 'group' in 'groups'

        // Iterate through items.
        $.each(items, function () {
            console.log(this.text); // Here 'this' points to an 'item' in 'items'
        });
    });
});

Or more simply:

$.getJSON(url, function (data) {
    $.each(data.response.venue.tips.groups, function (index, value) {
        $.each(this.items, function () {
            console.log(this.text);
        });
    });
});

In the JSON you specified, the last one would be:

$.getJSON(url, function (data) {
    // Get the 'items' from the first group.
    var items = data.response.venue.tips.groups[0].items;

    // Find the last index and the last item.
    var lastIndex = items.length - 1;
    var lastItem = items[lastIndex];

    console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
    console.log("Date: " + lastItem.createdAt);
    console.log("Text: " + lastItem.text);
});

This would give you:

User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How do I set an absolute include path in PHP?

hey all...i had a similar problem with my cms system. i needed a hard path for some security aspects. think the best way is like rob wrote. for quick an dirty coding think this works also..:-)

<?php
$path   = getcwd(); 
$myfile = "/test.inc.php";

/* 

getcwd () points to: /usr/srv/apache/htdocs/myworkingdir (as example)

echo ($path.$myfile);
would return...

/usr/srv/apache/htdocs/myworkingdir/test.inc.php

access outside your working directory is not allowed.
*/


includ_once ($path.$myfile);

//some code

?>

nice day strtok

CSS Float: Floating an image to the left of the text

Is this what you're after?

  • I changed your title into a h3 (header) tag, because it's a more semantic choice than using a div.

Live Demo #1
Live Demo #2 (with header at top, not sure if you wanted that)

HTML:

<div class="post-container">                
    <div class="post-thumb"><img src="http://dummyimage.com/200x200/f0f/fff" /></div>
    <div class="post-content">
        <h3 class="post-title">Post title</h3>
        <p>post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc post desc </p>
   </div>
</div>

CSS:

.post-container {
    margin: 20px 20px 0 0;  
    border: 5px solid #333;
    overflow: auto
}
.post-thumb {
    float: left
}
.post-thumb img {
    display: block
}
.post-content {
    margin-left: 210px
}
.post-title {
    font-weight: bold;
    font-size: 200%
}

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

JQuery create a form and add elements to it programmatically

You need to append form itself to body too:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);

How can I install a .ipa file to my iPhone simulator

With Xcode 6:

It's very possible to build and install on a simulator.

I did it by copying the debug build configuration (I called it SimRelease for my example below) in the project settings. I changed the architectures to i386 and x86_64 (not sure how necessary this was), but key difference to change between the copied build configuration is build for active architecture set to NO. After that a couple simple command line tools will do the rest!

xcodebuild -scheme YOUR_SCHEME -configuration SimRelease -sdk iphonesimulator8.1

Depending on where you have your DerivedData set you need to go find the outputted .app folder. Once you've found it you can simply install it on any simulator device. To find the device UUID's open Xcode and go to Window->Devices you'll see the list of the device instances and you can grab the UUID's. For a trivial script you could grab all of them from: ~/Library/Developer/CoreSimulator/Devices/ and install on every device.

From there the simple command to install on a device is:

xcrun simctl install DEVICE_ID APP_FOLDER_LOCATION

Here's a simple shell script to take the app and install it on every device:

app_dir=$1
current_dir=$(pwd)
cd ~/Library/Developer/CoreSimulator/Devices/
devices=$(ls -d */)
cd "$current_dir"
for device in $devices
do
    device_id=${device%/}
    xcrun simctl install "$device_id" "$app_dir"
done

Hope this helps! Took me a while to figure out the best way to do it.

mysql update query with sub query

Thanks, I didn't have the idea of an UPDATE with INNER JOIN.

In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.

UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
  FROM PicksPoints
  WHERE UserCompetitionID is not NULL
  -- put the join condition INSIDE the subquery :
  AND CompetitionID =  Competition.CompetitionID
  group by CompetitionID
) -- no table alias

should do the trick for every record of Competition.

To be noticed :

The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.

Since SELECT id, COUNT(*) GROUP BY id will only count for existing values of ids,

whereas a SELECT COUNT(*) will always return a value, being 0 if no records are selected.

This may, or may not, be a problem for you.

0-aware version of mellamokb query would be :

Update Competition as C
LEFT join (
  select CompetitionId, count(*) as NumberOfTeams
  from PicksPoints as p
  where UserCompetitionID is not NULL
  group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

Difference between "querySelector" and "querySelectorAll"

_x000D_
_x000D_
//querySelector returns single element_x000D_
let listsingle = document.querySelector('li');_x000D_
console.log(listsingle);_x000D_
_x000D_
_x000D_
//querySelectorAll returns lit/array of elements_x000D_
let list = document.querySelectorAll('li');_x000D_
console.log(list);_x000D_
_x000D_
_x000D_
//Note : output will be visible in Console
_x000D_
<ul>_x000D_
<li class="test">ffff</li>_x000D_
<li class="test">vvvv</li>_x000D_
<li>dddd</li>_x000D_
<li class="test">ddff</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

regular expression for Indian mobile numbers

var PHONE_REGEXP = /^[789]\d{9}$/;

this works for ng-pattern in angularjs or in javascript or any js framework

java.nio.file.Path for a classpath resource

This one works for me:

return Paths.get(ClassLoader.getSystemResource(resourceName).toURI());

Contain an image within a div?

Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.

#container img {
    max-height: 250px;
    max-width: 250px;
} 

See my example with an image that isn't a square, it doesn't stretch

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

List all kafka topics

Commands:

  1. To start the kafka:

    $ nohup ~/kafka/bin/kafka-server-start.sh ~/kafka/config/server.properties > ~/kafka/kafka.log 2>&1 &

  2. To list out all the topic on on kafka;

    $ bin/kafka-topics.sh --list --zookeeper localhost:2181

  3. To check the data is landing on kafka topic and to print it out;

    $ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic your_topic_name --from-beginning

Getting today's date in YYYY-MM-DD in Python?

Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

This module is clever enough to understand what you mean.

Just do pip install arrow.

Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternative approaches to dealing with dates in Python. That's mostly what I meant to suggest.

How to set Angular 4 background image?

You can use ngStyle to set background for a div

<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>

or you can also use built in background style:

<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>

Return multiple values to a method caller

Mainly two methods are there. 1. Use out/ref parameters 2. Return an Array of objects

Where to place the 'assets' folder in Android Studio?

In android studio you can specify where the source, res, assets folders are located. for each module/app in the build.gradle file you can add something like:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    sourceSets {
        main {
            java.srcDirs = ['src']
            assets.srcDirs = ['assets']
            res.srcDirs = ['res']
            manifest.srcFile 'AndroidManifest.xml'
        }
    }
}

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

Android - Center TextView Horizontally in LinearLayout

Just use: android:layout_centerHorizontal="true"

It will put the whole textview in the center

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

Bind TextBox on Enter-key press

Answered here quite elegantly using attached behaviors, my preferred method for almost anything.

WPF how to make textbox lose focus after hitting enter

How make background image on newsletter in outlook?

Powerful tool for "Bulletproof Email Background Images" (VML for Outlook 2007/2010/2013, and HTML/CSS for Outlook 2000/2003, Gmail, Hotmail...)

http://emailbg.net

as an exemple :

    <div style="background-color:#f6f6f6;">
  <!--[if gte mso 9]>
  <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
    <v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
  </v:background>
  <![endif]-->
  <table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td valign="top" align="left" background="http://i.imgur.com/n8Q6f.png">
      </td>
    </tr>
  </table>
</div>

in order to have the specified background image to Full email body.

This link help to use the Vector Markup Language (VML)

msdn.microsoft.com/en-us/library/bb264137%28v=vs.85%29.aspx

www.w3.org/TR/NOTE-VML#_Toc416858389

Take the content of a list and append it to another list

Using the map() and reduce() built-in functions

def file_to_list(file):
     #stuff to parse file to a list
     return list

files = [...list of files...]

L = map(file_to_list, files)

flat_L = reduce(lambda x,y:x+y, L)

Minimal "for looping" and elegant coding pattern :)

Filter output in logcat by tagname

use this:

adb logcat -s "TAGNAME"

Network tools that simulate slow network connection

DummyNet

Try this FreeBSD based VMWare image. It also has an excellent how-to, purely free and stands up in 20 minutes.

Update: DummyNet also supports Linux, OSX and Windows by now

How to get 0-padded binary representation of an integer in java?

There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")

Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

How to perform element-wise multiplication of two lists?

Use a list comprehension mixed with zip():.

[a*b for a,b in zip(lista,listb)]

Change the value in app.config file dynamically

This code works for me:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

How to throw std::exceptions with variable messages?

Use string literal operator if C++14 (operator ""s)

using namespace std::string_literals;

throw std::exception("Could not load config file '"s + configfile + "'"s);

or define your own if in C++11. For instance

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, str + len);
}

Your throw statement will then look like this

throw std::exception("Could not load config file '"_s + configfile + "'"_s);

which looks nice and clean.

Get timezone from DateTime

Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.

The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.

As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.

What's the effect of adding 'return false' to a click event listener?

Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.

If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.

Conversion failed when converting date and/or time from character string while inserting datetime

I'm Tried this and it's working with me :

SELECT CONVERT(date, yourDate ,104)

How to get access to raw resources that I put in res folder?

An advance approach is using Kotlin Extension function

fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
    return resources.openRawResource(resourceId)
}

One more interesting thing is extension function use that is defined in Closeable scope

For example you can work with input stream in elegant way without handling Exceptions and memory managing

fun Context.readRaw(@RawRes resourceId: Int): String {
    return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}

How to tell if UIViewController's view is visible

I needed this to check if the view controller is the current viewed controller, I did it via checking if there's any presented view controller or pushed through the navigator, I'm posting it in case anyone needed such a solution:

if presentedViewController != nil || navigationController?.topViewController != self {
      //Viewcontroller isn't viewed
}else{
     // Now your viewcontroller is being viewed 
}

Create a tar.xz in one command

Use the -J compression option for xz. And remember to man tar :)

tar cfJ <archive.tar.xz> <files>

Edit 2015-08-10:

If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:

tar -cJf <archive.tar.xz> <files>

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

How do I copy a string to the clipboard?

Code snippet to copy the clipboard:

Create a wrapper Python code in a module named (clipboard.py):

import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Clipboard
def setText(text):
    Clipboard.SetText(text)

def getText():
    return Clipboard.GetText()

Then import the above module into your code.

import io
import clipboard
code = clipboard.getText()
print code
code = "abcd"
clipboard.setText(code)

I must give credit to the blog post Clipboard Access in IronPython.

Git: Could not resolve host github.com error while cloning remote repository in git

Would like to note, when I did Brian's solution:

git config --global --unset http.proxy

make sure to quit and restart terminal. Mine didn't resolve until I did that.

Thanks so much, issue was killing me!

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Bootstrap Element 100% Width

I would use two separate 'container' div as below:

<div class="container">
   /* normal*/
</div>
<div class="container-fluid">
   /*full width container*/
</div>

Bare in mind that container-fluid does not follow your breakpoints and it is a full width container.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.

declare @schema varchar(100), @table varchar(100)
set @schema = 'dbo' -- set schema name here
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into  @sql(s) values ('create table [' + @table + '] (')

-- column list
insert into @sql(s)
select 
    '  ['+column_name+'] ' + 
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists ( 
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
    ) then
        'IDENTITY(' + 
        cast(ident_seed(@table) as varchar) + ',' + 
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
 order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        where constraint_name = @pkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("http://example.com/path/to/the/file");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

Multiline text in JLabel

It is possible to use (basic) CSS in the HTML.


This question was linked from Multiline JLabels - Java.

How to get current time in python and break up into year, month, day, hour, minute?

Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)

>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

how to read System environment variable in Spring applicationContext

In your bean definition, make sure to include "searchSystemEnvironment" and set it to "true". And if you're using it to build a path to a file, specify it as a file:/// url.

So for example, if you have a config file located in

/testapp/config/my.app.config.properties

then set an environment variable like so:

MY_ENV_VAR_PATH=/testapp/config

and your app can load the file using a bean definition like this:

e.g.

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="searchContextAttributes" value="true" />
    <property name="contextOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value>
        </list>
    </property>
</bean>

JavaScript checking for null vs. undefined and difference between == and ===

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
var data;  //The Values can be like as null, blank, undefined, zero you can test

if(!(!(data)))
{
   //If data has valid value
    alert("data "+data);
} 
else 
{
    //If data has null, blank, undefined, zero etc.
    alert("data is "+data);
}

}

JUnit 4 compare Sets

A particularly interesting case is when you compare

   java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]> 

and

   java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>

So far, the only solution I see is to change both of them into sets

assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));

Or I could compare them element by element.

Setting Action Bar title and subtitle

You can set the title in action-bar using AndroidManifest.xml. Add label to the activity

<activity
            android:name=".YourActivity"
            android:label="Your Title" />

What svn command would list all the files modified on a branch?

echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl

Assign value from successful promise resolve to external variable

This is one "trick" you can do since your out of an async function so can't use await keywork

Do what you want to do with vm.feed inside a setTimeout

vm.feed = getFeed().then(function(data) {return data;});

 setTimeout(() => {
    // do you stuf here
    // after the time you promise will be revolved or rejected
    // if you need some of the values in here immediately out of settimeout
    // might occur an error if promise wore not yet resolved or rejected
    console.log("vm.feed",vm.feed);
 }, 100);

'react-scripts' is not recognized as an internal or external command

If react-scripts is present in package.json, then just type this command

npm install

If react-scripts is not present in package.json, then you probably haven't installed it. To do that, run:

npm install react-scripts --save

php foreach with multidimensional array

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});

Insert text into textarea with jQuery

If you want to append content to the textarea without replacing them, You can try the below

$('textarea').append('Whatever need to be added');

According to your scenario it would be

$('a').click(function() 
{ 
  $('textarea').append($('#area').val()); 
})

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

How to pass multiple values to single parameter in stored procedure

I think, below procedure help you to what you are looking for.

 CREATE PROCEDURE [dbo].[FindEmployeeRecord]
        @EmployeeID nvarchar(Max)
    AS
    BEGIN
    DECLARE @sqLQuery VARCHAR(MAX)
    Declare @AnswersTempTable Table
    (  
        EmpId int,         
        EmployeeName nvarchar (250),       
        EmployeeAddress nvarchar (250),  
        PostalCode nvarchar (50),
        TelephoneNo nvarchar (50),
        Email nvarchar (250),
        status nvarchar (50),  
        Sex nvarchar (50) 
    )

    Set @sqlQuery =
    'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
    from Employee e
    join EmployeeDetail ed on e.Empid = ed.iEmpID
    where Convert(nvarchar(Max),e.EmpId) in ('+@EmployeeId+')
    order by EmpId'
    Insert into @AnswersTempTable
    exec (@sqlQuery)
    select * from @AnswersTempTable
    END

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

How do you configure HttpOnly cookies in tomcat / java webapps?

Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.

private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
    if (response.containsHeader("SET-COOKIE")) {
        String sessionid = request.getSession().getId();
        String contextPath = request.getContextPath();
        String secure = "";
        if (request.isSecure()) {
            secure = "; Secure"; 
        }
        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
                         + "; Path=" + contextPath + "; HttpOnly" + secure);
    }
}

php date validation

Use it:

function validate_Date($mydate,$format = 'DD-MM-YYYY') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);       

    if (is_numeric($year) && is_numeric($month) && is_numeric($day))
        return checkdate($month,$day,$year);
    return false;           
}         

Copy data from one column to other column (which is in a different table)

Here the query:

Same Table:

UPDATE table_name 
SET column1 = column2

Different Table:

UPDATE table_name1 
    SET column1 = (
        SELECT column2
        FROM table_name2
        WHERE table_name1.id = table_name2.id
    );

How to remove "disabled" attribute using jQuery?

Use like this,

HTML:

<input type="text" disabled="disabled" class="inputDisabled" value="">

<div id="edit">edit</div>

JS:

 $('#edit').click(function(){ // click to
            $('.inputDisabled').attr('disabled',false); // removing disabled in this class
 });

What does 'var that = this;' mean in JavaScript?

Sometimes this can refer to another scope and refer to something else, for example suppose you want to call a constructor method inside a DOM event, in this case this will refer to the DOM element not the created object.

HTML

<button id="button">Alert Name</button>

JS

var Person = function(name) {
  this.name = name;
  var that = this;
  this.sayHi = function() {
    alert(that.name);
  };
};

var ahmad = new Person('Ahmad');
var element = document.getElementById('button');
element.addEventListener('click', ahmad.sayHi); // => Ahmad

Demo

The solution above will assing this to that then we can and access the name property inside the sayHi method from that, so this can be called without issues inside the DOM call.

Another solution is to assign an empty that object and add properties and methods to it and then return it. But with this solution you lost the prototype of the constructor.

var Person = function(name) {
  var that = {};
  that.name = name;
  that.sayHi = function() {
    alert(that.name);
  };
  return that;
};

How to get ID of the last updated row in MySQL?

My solution is , first decide the "id" ( @uids ) with select command and after update this id with @uids .

SET @uids := (SELECT id FROM table WHERE some = 0 LIMIT 1);
UPDATE table SET col = 1 WHERE id = @uids;SELECT @uids;

it worked on my project.

Use ASP.NET MVC validation with jquery ajax?

Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:

Created a action filter to get errors for ajax request:

public class ValidateAjaxAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
                return;

            var modelState = filterContext.Controller.ViewData.ModelState;
            if (!modelState.IsValid)
            {
                var errorModel =
                        from x in modelState.Keys
                        where modelState[x].Errors.Count > 0
                        select new
                        {
                            key = x,
                            errors = modelState[x].Errors.
                                                          Select(y => y.ErrorMessage).
                                                          ToArray()
                        };
                filterContext.Result = new JsonResult()
                {
                    Data = errorModel
                };
                filterContext.HttpContext.Response.StatusCode =
                                                      (int)HttpStatusCode.BadRequest;
            }
        }
    }

Added the filter to my controller method as:

[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
    return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}

Added a common script for jquery validation:

function onAjaxFormError(data) {
    var form = this;
    var errorResponse = data.responseJSON;
    $.each(errorResponse, function (index, value) {
        // Element highlight
        var element = $(form).find('#' + value.key);
        element = element[0];
        highLightError(element, 'input-validation-error');

        // Error message
        var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
        validationMessageElement.removeClass('field-validation-valid');
        validationMessageElement.addClass('field-validation-error');
        validationMessageElement.text(value.errors[0]);
    });
}

$.validator.setDefaults({
            ignore: [],
            highlight: highLightError,
            unhighlight: unhighlightError
        });

var highLightError = function(element, errorClass) {
    element = $(element);
    element.addClass(errorClass);
}

var unhighLightError = function(element, errorClass) {
    element = $(element);
    element.removeClass(errorClass);
}

Finally added the error javascript method to my Ajax Begin form:

@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}

How to get records randomly from the oracle database?

SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

How to copy a file to a remote server in Python using SCP or SSH?

You can do something like this, to handle the host key checking as well

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Is JavaScript a pass-by-reference or pass-by-value language?

This is little more explanation for pass by value and pass by reference (JavaScript). In this concept, they are talking about passing the variable by reference and passing the variable by reference.

Pass by value (primitive type)

var a = 3;
var b = a;

console.log(a); // a = 3
console.log(b); // b = 3

a=4;
console.log(a); // a = 4
console.log(b); // b = 3
  • applies to all primitive type in JavaScript (string, number, Boolean, undefined, and null).
  • a is allocated a memory (say 0x001) and b creates a copy of the value in memory (say 0x002).
  • So changing the value of a variable doesn't affect the other, as they both reside in two different locations.

Pass by reference (objects)

var c = { "name" : "john" };
var d = c;

console.log(c); // { "name" : "john" }
console.log(d); // { "name" : "john" }

c.name = "doe";

console.log(c); // { "name" : "doe" }
console.log(d); // { "name" : "doe" }
  • The JavaScript engine assigns the object to the variable c, and it points to some memory, say (0x012).
  • When d=c, in this step d points to the same location (0x012).
  • Changing the value of any changes value for both the variable.
  • Functions are objects

Special case, pass by reference (objects)

c = {"name" : "jane"};
console.log(c); // { "name" : "jane" }
console.log(d); // { "name" : "doe" }
  • The equal(=) operator sets up new memory space or address

is it possible to update UIButton title/text programmatically?

for swift :

button.setTitle("Swift", forState: UIControlState.Normal)                   

AngularJS ng-style with a conditional expression

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

How to use LINQ to select object with minimum or maximum property value

I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.

var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

Yarn install command error No such file or directory: 'install'

Just copy and paste this code one after on your terminal It worked perfectly well for me.

sudo apt remove cmdtest
sudo apt remove yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update
sudo apt-get install yarn -y

remove empty lines from text file with PowerShell

I found a nice one liner here >> http://www.pixelchef.net/remove-empty-lines-file-powershell. Just tested it out with several blanks lines including newlines only as well as lines with just spaces, just tabs, and combinations.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt

See the original for some notes about the code. Nice :)

Mailto: Body formatting

Use %0D%0A for a line break in your body

Example (Demo):

<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
                                                                  ^^^^^^

jQuery check/uncheck radio button onclick

If you use on click and only check if radio is checked and then deselect, you will never get the radio checked. So maybe easiest is to use classnames like this:

if($(this).hasClass('alreadyChecked')) {//it is already checked
        $('.myRadios').removeClass('alreadyChecked');//remove from all radios
        $(this).prop('checked', false);//deselect this
    }
    else {
        $('.myRadios').removeClass('alreadyChecked');//remove from all
        $(this).addClass('alreadyChecked');//add to only this
    }

How to create an executable .exe file from a .m file

Try:

mcc -m yourfile

Also see help mcc

Convert object string to JSON

This will also work

let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));

C++ IDE for Linux?

I've previously used Ultimate++ IDE and it's rather good.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Remove the space or empty line in server.xml or context.xml at the beginning of your code

Sum all the elements java arraylist

Not very hard, just use m.get(i) to get the value from the list.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum += m.get(i);
    }
    return sum;
}

React Error: Target Container is not a DOM Element

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

How to handle errors with boto3?

I found it very useful, since the Exceptions are not documented, to list all exceptions to the screen for this package. Here is the code I used to do it:

import botocore.exceptions
def listexns(mod):
    #module = __import__(mod)
    exns = []
    for name in botocore.exceptions.__dict__:
        if (isinstance(botocore.exceptions.__dict__[name], Exception) or
            name.endswith('Error')):
            exns.append(name)
    for name in exns:
        print('%s.%s is an exception type' % (str(mod), name))
    return

if __name__ == '__main__':
    import sys
    if len(sys.argv) <= 1:
        print('Give me a module name on the $PYTHONPATH!')
    print('Looking for exception types in module: %s' % sys.argv[1])
    listexns(sys.argv[1])

Which results in:

Looking for exception types in module: boto3
boto3.BotoCoreError is an exception type
boto3.DataNotFoundError is an exception type
boto3.UnknownServiceError is an exception type
boto3.ApiVersionNotFoundError is an exception type
boto3.HTTPClientError is an exception type
boto3.ConnectionError is an exception type
boto3.EndpointConnectionError is an exception type
boto3.SSLError is an exception type
boto3.ConnectionClosedError is an exception type
boto3.ReadTimeoutError is an exception type
boto3.ConnectTimeoutError is an exception type
boto3.ProxyConnectionError is an exception type
boto3.NoCredentialsError is an exception type
boto3.PartialCredentialsError is an exception type
boto3.CredentialRetrievalError is an exception type
boto3.UnknownSignatureVersionError is an exception type
boto3.ServiceNotInRegionError is an exception type
boto3.BaseEndpointResolverError is an exception type
boto3.NoRegionError is an exception type
boto3.UnknownEndpointError is an exception type
boto3.ConfigParseError is an exception type
boto3.MissingParametersError is an exception type
boto3.ValidationError is an exception type
boto3.ParamValidationError is an exception type
boto3.UnknownKeyError is an exception type
boto3.RangeError is an exception type
boto3.UnknownParameterError is an exception type
boto3.AliasConflictParameterError is an exception type
boto3.PaginationError is an exception type
boto3.OperationNotPageableError is an exception type
boto3.ChecksumError is an exception type
boto3.UnseekableStreamError is an exception type
boto3.WaiterError is an exception type
boto3.IncompleteReadError is an exception type
boto3.InvalidExpressionError is an exception type
boto3.UnknownCredentialError is an exception type
boto3.WaiterConfigError is an exception type
boto3.UnknownClientMethodError is an exception type
boto3.UnsupportedSignatureVersionError is an exception type
boto3.ClientError is an exception type
boto3.EventStreamError is an exception type
boto3.InvalidDNSNameError is an exception type
boto3.InvalidS3AddressingStyleError is an exception type
boto3.InvalidRetryConfigurationError is an exception type
boto3.InvalidMaxRetryAttemptsError is an exception type
boto3.StubResponseError is an exception type
boto3.StubAssertionError is an exception type
boto3.UnStubbedResponseError is an exception type
boto3.InvalidConfigError is an exception type
boto3.InfiniteLoopConfigError is an exception type
boto3.RefreshWithMFAUnsupportedError is an exception type
boto3.MD5UnavailableError is an exception type
boto3.MetadataRetrievalError is an exception type
boto3.UndefinedModelAttributeError is an exception type
boto3.MissingServiceIdError is an exception type

Angular2 Material Dialog css, dialog size

On smaller screen's like laptop the dialog will shrink. To auto-fix, try the following option

http://answersicouldntfindanywhereelse.blogspot.com/2018/05/angular-material-full-size-dialog-on.html

Additional Reading https://material.angular.io/cdk/layout/overview

Thanks to the solution in answersicouldntfindanywhereelse (2nd para). it worked for me.

Following is needed

import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout'

How can I disable the Maven Javadoc plugin from the command line?

Add to the release plugin config in the root-level pom.xml:

<configuration>
    <arguments>-Dmaven.javadoc.skip=true</arguments>
</configuration>

Free XML Formatting tool

Advanced Conventional Formatting [Update]

XMLSpectrum is an open source syntax-highlighter. Supporting XML - but with special features for XSLT 2.0, XSD 1.1 and XPath 2.0. I'm mentioning this here because it also has special formatting capabilities for XML: it vertically aligns attributes and their contents as well as elements - to enhance XML readability.

The output HTML is suitable for reviewing in a browser or if the XML needs further editing it can be copied and pasted into an XML editor of your choice

Because xmlspectrum.xsl uses its own XML text parser, all content such as entity references and CDATA sections are preserved - as in an editor.

enter image description here

Note on usage: this is just an XSLT 2.0 stylesheet so you would need to enclose the required command-line (samples provided) in a small script so you could automatically transform the XML source.

Virtual Formatting

XMLQuire is a free XML editor that has special formatting capabilities - it formats XML properly, including multi-line attributes, attribute-values, word-wrap indentation and even XML comments.

All XML indentation is done without inserting tabs or spaces, ensuring the integrity of the XML is maintained. For versions of Windows later than XP, no installation is needed, its just a 3MB .exe file.

If you need to print out the formatted XML there are special options within the print-preview, such as line-numbering that follows the indentation. If you need to copy the formatted XML to a word processor as rich text, that's available too.

[Disclosure: I maintain both XMLQuire and XMLSpectrum as 'home projects']

PHP: Split a string in to an array foreach char

Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

If the script always outputs lines of 10 characters followed by 3 extra (in other words, you just want the first 10 characters), you can use

script | cut -c 1-10

If it outputs an uncertain number of non-space characters, followed by a space and then 2 other extra characters (in other words, you just want the first field), you can use

script | cut -d ' ' -f 1

... as in majhool's comment earlier. Depending on your platform, you may also have colrm, which, again, would work if the lines are a fixed length:

script | colrm 11

Is there a way to access an iteration-counter in Java's for-each loop?

If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.

rand() returns the same number each time the program is run

random functions like borland complier

using namespace std;

int sys_random(int min, int max) {
   return (rand() % (max - min+1) + min);
}

void sys_randomize() {
    srand(time(0));
}

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ReactJS - Add custom event listener to component

You could use componentDidMount and componentWillUnmount methods:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MovieItem extends Component
{
    _handleNVEvent = event => {
        ...
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
    }

    componentWillUnmount() {
        ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
    }

    [...]

}

export default MovieItem;

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

How to prevent Screen Capture in Android

I used this solution to allow manual snapshot in app while disallowing screen capture when the app goes in background, hope it helps.

@Override
protected void onResume() {
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    super.onResume();
}

@Override
protected void onPause() {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    super.onPause();
}

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to Deep clone in javascript

Avoid use this method

let cloned = JSON.parse(JSON.stringify(objectToClone));

Why? this method will convert 'function,undefined' to null

const myObj = [undefined, null, function () {}, {}, '', true, false, 0, Symbol];

const IsDeepClone = JSON.parse(JSON.stringify(myObj));

console.log(IsDeepClone); //[null, null, null, {…}, "", true, false, 0, null]

try to use deepClone function.There are several above

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Formatting MM/DD/YYYY dates in textbox in VBA

This is the same concept as Siddharth Rout's answer. But I wanted a date picker which could be fully customized so that the look and feel could be tailored to whatever project it's being used in.

You can click this link to download the custom date picker I came up with. Below are some screenshots of the form in action.

Three example calendars

To use the date picker, simply import the CalendarForm.frm file into your VBA project. Each of the calendars above can be obtained with one single function call. The result just depends on the arguments you use (all of which are optional), so you can customize it as much or as little as you want.

For example, the most basic calendar on the left can be obtained by the following line of code:

MyDateVariable = CalendarForm.GetDate

That's all there is to it. From there, you just include whichever arguments you want to get the calendar you want. The function call below will generate the green calendar on the right:

MyDateVariable = CalendarForm.GetDate( _
    SelectedDate:=Date, _
    DateFontSize:=11, _
    TodayButton:=True, _
    BackgroundColor:=RGB(242, 248, 238), _
    HeaderColor:=RGB(84, 130, 53), _
    HeaderFontColor:=RGB(255, 255, 255), _
    SubHeaderColor:=RGB(226, 239, 218), _
    SubHeaderFontColor:=RGB(55, 86, 35), _
    DateColor:=RGB(242, 248, 238), _
    DateFontColor:=RGB(55, 86, 35), _
    SaturdayFontColor:=RGB(55, 86, 35), _
    SundayFontColor:=RGB(55, 86, 35), _
    TrailingMonthFontColor:=RGB(106, 163, 67), _
    DateHoverColor:=RGB(198, 224, 180), _
    DateSelectedColor:=RGB(169, 208, 142), _
    TodayFontColor:=RGB(255, 0, 0), _
    DateSpecialEffect:=fmSpecialEffectRaised)

Here is a small taste of some of the features it includes. All options are fully documented in the userform module itself:

  • Ease of use. The userform is completely self-contained, and can be imported into any VBA project and used without much, if any additional coding.
  • Simple, attractive design.
  • Fully customizable functionality, size, and color scheme
  • Limit user selection to a specific date range
  • Choose any day for the first day of the week
  • Include week numbers, and support for ISO standard
  • Clicking the month or year label in the header reveals selectable comboboxes
  • Dates change color when you mouse over them

How to use global variable in node.js?

If your app is written in TypeScript, try

(global as any).logger = // ...

or

Object.assign(global, { logger: // ... })

However, I will do it only when React Native's __DEV__ in testing environment.

Altering a column to be nullable

ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT null;

This will work for you.

If you want to change a not null column to allow null, no need to include not null clause. Because default columns get not null.

ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT;

Why do I get a warning icon when I add a reference to an MEF plugin project?

Thank you all for the help. Here is a breakdown of how I fixed my problem:

Right click on your project > Properties

Under Application change the target Framework. In my case ImageSharp was using .Net 4.6.1. You can find this in your packages.config.

Go to your project references. You'll notice SixLabors has a yellow triangle. You have to update the NuGet package.

Right click on References > Manage NuGet Packages.

Update SixLabors.

You might have slight code updates (see below) but this fixed my problem.

Convert ImageSharp.Image to ImageSharp.PixelFormats.Rgba32?

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

Sending JSON object to Web API

var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    success: function (data) {
        alert('success');
    },
    error: function (error) {
        jsonValue = jQuery.parseJSON(error.responseText);
        jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"

your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

pthread function from a class

This is a bit old question but a very common issue which many face. Following is a simple and elegant way to handle this by using std::thread

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

class foo
{
    public:
        void bar(int j)
        {
            n = j;
            for (int i = 0; i < 5; ++i) {
                std::cout << "Child thread executing\n";
                ++n;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        int n = 0;
};

int main()
{
    int n = 5;
    foo f;
    std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    std::cout << "Main Thread running as usual";
    class_thread.join();
    std::cout << "Final value of foo::n is " << f.n << '\n';
}

Above code also takes care of passing argument to the thread function.

Refer std::thread document for more details.

What is the most effective way for float and double comparison?

Unfortunately, even your "wasteful" code is incorrect. EPSILON is the smallest value that could be added to 1.0 and change its value. The value 1.0 is very important — larger numbers do not change when added to EPSILON. Now, you can scale this value to the numbers you are comparing to tell whether they are different or not. The correct expression for comparing two doubles is:

if (fabs(a - b) <= DBL_EPSILON * fmax(fabs(a), fabs(b)))
{
    // ...
}

This is at a minimum. In general, though, you would want to account for noise in your calculations and ignore a few of the least significant bits, so a more realistic comparison would look like:

if (fabs(a - b) <= 16 * DBL_EPSILON * fmax(fabs(a), fabs(b)))
{
    // ...
}

If comparison performance is very important to you and you know the range of your values, then you should use fixed-point numbers instead.

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

How to open a web page from my application?

The old school way ;)

public static void openit(string x) {
   System.Diagnostics.Process.Start("cmd", "/C start" + " " + x); 
}

Use: openit("www.google.com");

How do I set ANDROID_SDK_HOME environment variable?

This worked for me:

  1. Open control panel
  2. click System
  3. Then go to Change Environment Variables
  4. Then click create a new environment variables
  5. Create a new variable named ANDROID_HOME path C:\Android\sdk

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

jquery ajax get responsetext from http url

You simply must rewrite it like that:

var response = '';
$.ajax({ type: "GET",   
         url: "http://www.google.de",   
         async: false,
         success : function(text)
         {
             response = text;
         }
});

alert(response);

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

How to display list of repositories from subversion server

If your server is Apache, you should be able to configure it to see the repository list with viewvc - this is the most basic one, other more complex interfaces exist but this is not your purpose here.

In some versions, ViewVC is an option of the standard installation now, for instance from Collabnet.

Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.

From there, you will have to:

  • get the HTML page,
  • extract the list, and
  • process it for the individual repository search.

Unfortunately in this case I cannot think of something more straightforward.

There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn directly from Python if you prefer.

If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).

Autowiring two beans implementing same interface - how to set default bean to autowire?

I'd suggest marking the Hibernate DAO class with @Primary, i.e. (assuming you used @Repository on HibernateDeviceDao):

@Primary
@Repository
public class HibernateDeviceDao implements DeviceDao

This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.

Also, rather than using @Autowired @Qualifier, I find it more elegant to use @Resource for picking specific beans, i.e.

@Resource(name="jdbcDeviceDao")
DeviceDao deviceDao;

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How can I get (query string) parameters from the URL in Next.js?

Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
Or
import Router from 'next/router'

Router.push({
    pathname: '/search',
    query: { keyword: 'this way' },
})

In Component

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  console.log(router.query);

  ...
}

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

Try adding C:\Program Files\Nodejs to your PATH environment variable. The PATH environment variable allows run executables or access files within the folders specified (separated by semicolons).

On the command prompt, the command would be set PATH=%PATH%;C:\Program Files\Nodejs.

How do you convert CString and std::string std::wstring to each other?

This works fine:

//Convert CString to std::string
inline std::string to_string(const CString& cst)
{
    return CT2A(cst.GetString());
}

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Bin size in Matplotlib (Histogram)

For N bins, the bin edges are specified by list of N+1 values where the first N give the lower bin edges and the +1 gives the upper edge of the last bin.

Code:

from numpy import np; from pylab import *

bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.linspace(min_edge, max_edge, Nplus1)

Note that linspace produces array from min_edge to max_edge broken into N+1 values or N bins

Why Maven uses JDK 1.6 but my java -version is 1.7

You can also do,

<properties>
      ...  

      <!-- maven-compiler-plugin , aka JAVA Compiler 1.7 -->
      <maven.compiler.target>1.7</maven.compiler.target>
      <maven.compiler.source>1.7</maven.compiler.source>

      ...  
</properties>

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How to compile Go program consisting of multiple files?

When you separate code from main.go into for example more.go, you simply pass that file to go build/go run/go install as well.

So if you previously ran

go build main.go

you now simply

go build main.go more.go

As further information:

go build --help

states:

If the arguments are a list of .go files, build treats them as a list of source files specifying a single package.


Notice that go build and go install differ from go run in that the first two state to expect package names as arguments, while the latter expects go files. However, the first two will also accept go files as go install does.

If you are wondering: build will just build the packages/files, install will produce object and binary files in your GOPATH, and run will compile and run your program.

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I would imagine that the caching DNS servers you're using aren't behaving properly (or the DNS server for the domain you're resolving isn't working properly). You can try to fix the former possibility.

Do you have at least 2 name servers registered on your network adapter? You could always swap your computer over to use a different caching DNS server to rule this out. Try Google's:

8.8.8.8
8.8.4.4

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

How do you represent a JSON array of strings?

String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";

This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to @cregox...

A bit complicated but can explain a lot in a single JSON string.

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

How to add headers to a multicolumn listbox in an Excel userform using VBA

I was searching for quite a while for a solution to add a header without using a separate sheet and copy everything into the userform.

My solution is to use the first row as header and run it through an if condition and add additional items underneath.

Like that:

_x000D_
_x000D_
If lborowcount = 0 Then_x000D_
 With lboorder_x000D_
 .ColumnCount = 5_x000D_
 .AddItem_x000D_
 .Column(0, lborowcount) = "Item"_x000D_
 .Column(1, lborowcount) = "Description"_x000D_
 .Column(2, lborowcount) = "Ordered"_x000D_
 .Column(3, lborowcount) = "Rate"_x000D_
 .Column(4, lborowcount) = "Amount"_x000D_
 End With_x000D_
 lborowcount = lborowcount + 1_x000D_
End If_x000D_
        _x000D_
        _x000D_
With lboorder_x000D_
 .ColumnCount = 5_x000D_
 .AddItem_x000D_
 .Column(0, lborowcount) = itemselected_x000D_
 .Column(1, lborowcount) = descriptionselected_x000D_
 .Column(2, lborowcount) = orderedselected_x000D_
 .Column(3, lborowcount) = rateselected_x000D_
 .Column(4, lborowcount) = amountselected_x000D_
 _x000D_
 _x000D_
 End With_x000D_
_x000D_
lborowcount = lborowcount + 1
_x000D_
_x000D_
_x000D_

in that example lboorder is the listbox, lborowcount counts at which row to add the next listbox item. It's a 5 column listbox. Not ideal but it works and when you have to scroll horizontally the "header" stays above the row.

Get the key corresponding to the minimum value within a dictionary

Here's an answer that actually gives the solution the OP asked for:

>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1]) 
(321, 0)

Using d.iteritems() will be more efficient for larger dictionaries, however.

c# datagridview doubleclick on row with FullRowSelect

For your purpose, there is a default event when the row header is double-clicked. Check the following code,

 private void dgvCustom_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
 {
      //Your code goes here
 }

What is dynamic programming?

Dynamic programming is a technique for solving problems with overlapping sub problems. A dynamic programming algorithm solves every sub problem just once and then Saves its answer in a table (array). Avoiding the work of re-computing the answer every time the sub problem is encountered. The underlying idea of dynamic programming is: Avoid calculating the same stuff twice, usually by keeping a table of known results of sub problems.

The seven steps in the development of a dynamic programming algorithm are as follows:

  1. Establish a recursive property that gives the solution to an instance of the problem.
  2. Develop a recursive algorithm as per recursive property
  3. See if same instance of the problem is being solved again an again in recursive calls
  4. Develop a memoized recursive algorithm
  5. See the pattern in storing the data in the memory
  6. Convert the memoized recursive algorithm into iterative algorithm
  7. Optimize the iterative algorithm by using the storage as required (storage optimization)

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

How to use Python's pip to download and keep the zipped files for a package?

pip wheel is another option you should consider:

pip wheel mypackage -w .\outputdir

It will download packages and their dependencies to a directory (current working directory by default), but it performs the additional step of converting any source packages to wheels.

It conveniently supports requirements files:

pip wheel -r requirements.txt -w .\outputdir

Add the --no-deps argument if you only want the specifically requested packages:

pip wheel mypackage -w .\outputdir --no-deps

get UTC time in PHP

Using gmdate will always return a GMT date. Syntax is same as for date.

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

What's a clean way to stop mongod on Mac OS X?

Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.

so, 1. get the pid of mongodb

$ pgrep mongo

you will get pid of mongo, Now

$ kill

You may use kill -15 as well

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

Installing Java 7 on Ubuntu

Download java jdk<version>-linux-x64.tar.gz file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.

Extract this file where you want. like: /home/java(Folder name created by user in home directory).

Now open terminal. Set path JAVA_HOME=path of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all) and paste here.

Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201

Let Ubuntu know where our JDK/JRE is located.

sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000

Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.

sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws

Now try:

$ sudo update-alternatives --config java

There are 3 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                  Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-6-oracle1/bin/java   1047      auto mode
  1            /usr/bin/gij-4.6                       1046      manual mode
  2            /usr/lib/jvm/java-6-oracle1/bin/java   1047      manual mode
  3            /usr/lib/jvm/jdk1.7.0_75/bin/java      1         manual mode

Press enter to keep the current choice [*], or type selection number: 3

update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode

Repeat the above for:

sudo update-alternatives --config javac
sudo update-alternatives --config javaws

Is there an operator to calculate percentage in Python?

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:

def percentage(percent, whole):
  return (percent * whole) / 100.0

wampserver doesn't go green - stays orange

Make a Ctrl+Alt+Suppr in order to see if no other Apache version is ever runing on your computer. It was the case for me, I just stop them and the light pass green!

Cheers!

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

Django Rest Framework File Upload

I solved this problem with ModelViewSet and ModelSerializer. Hope this will help community.

I also preffer to have validation and Object->JSON (and vice-versa) login in serializer itself rather than in views.

Lets understand it by example.

Say, I want to create FileUploader API. Where it will be storing fields like id, file_path, file_name, size, owner etc in database. See sample model below:

class FileUploader(models.Model):
    file = models.FileField()
    name = models.CharField(max_length=100) #name is filename without extension
    version = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now=True, db_index=True)
    owner = models.ForeignKey('auth.User', related_name='uploaded_files')
    size = models.IntegerField(default=0)

Now, For APIs this is what I want:

  1. GET:

When I fire the GET endpoint, I want all above fields for every uploaded file.

  1. POST:

But for user to create/upload file, why she has to worry about passing all these fields. She can just upload the file and then, I suppose, serializer can get rest of the fields from uploaded FILE.

Searilizer: Question: I created below serializer to serve my purpose. But not sure if its the right way to implement it.

class FileUploaderSerializer(serializers.ModelSerializer):
    # overwrite = serializers.BooleanField()
    class Meta:
        model = FileUploader
        fields = ('file','name','version','upload_date', 'size')
        read_only_fields = ('name','version','owner','upload_date', 'size')

   def validate(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
        validated_data['size'] = validated_data['file'].size
        #other validation logic
        return validated_data

    def create(self, validated_data):
        return FileUploader.objects.create(**validated_data)

Viewset for reference:

class FileUploaderViewSet(viewsets.ModelViewSet):
    serializer_class = FileUploaderSerializer
    parser_classes = (MultiPartParser, FormParser,)

    # overriding default query set
    queryset = LayerFile.objects.all()

    def get_queryset(self, *args, **kwargs):
        qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
        qs = qs.filter(owner=self.request.user)
        return qs

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();

Spring Boot and how to configure connection details to MongoDB?

It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>

gcc makefile error: "No rule to make target ..."

In my case it was due to a multi-line rule error in the Makefile. I had something like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o \
OBJS-$(CONFIG_OBJ2)            += file5.o 
OBJS-$(CONFIG_OBJ3)            += file6.o
...

The backslash at the end of file list in CONFIG_OBJ1's rule caused this error. It should be like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o
OBJS-$(CONFIG_OBJ2)            += file5.o
...

How to sort an array of ints using a custom comparator?

Here is some code (it's actually not Timsort as I originally thought, but it does work well) that does the trick without any boxing/unboxing. In my tests, it works 3-4 times faster than using Collections.sort with a List wrapper around the array.

// This code has been contributed by 29AjayKumar 
// from: https://www.geeksforgeeks.org/sort/

static final int sortIntArrayWithComparator_RUN = 32; 

// this function sorts array from left index to  
// to right index which is of size atmost RUN  
static void sortIntArrayWithComparator_insertionSort(int[] arr, IntComparator comparator, int left, int right) { 
    for (int i = left + 1; i <= right; i++)  
    { 
        int temp = arr[i]; 
        int j = i - 1; 
        while (j >= left && comparator.compare(arr[j], temp) > 0)
        { 
            arr[j + 1] = arr[j]; 
            j--; 
        } 
        arr[j + 1] = temp; 
    } 
} 

// merge function merges the sorted runs  
static void sortIntArrayWithComparator_merge(int[] arr, IntComparator comparator, int l, int m, int r) { 
    // original array is broken in two parts  
    // left and right array  
    int len1 = m - l + 1, len2 = r - m; 
    int[] left = new int[len1]; 
    int[] right = new int[len2]; 
    for (int x = 0; x < len1; x++)  
    { 
        left[x] = arr[l + x]; 
    } 
    for (int x = 0; x < len2; x++)  
    { 
        right[x] = arr[m + 1 + x]; 
    } 

    int i = 0; 
    int j = 0; 
    int k = l; 

    // after comparing, we merge those two array  
    // in larger sub array  
    while (i < len1 && j < len2)  
    { 
        if (comparator.compare(left[i], right[j]) <= 0)
        { 
            arr[k] = left[i]; 
            i++; 
        } 
        else 
        { 
            arr[k] = right[j]; 
            j++; 
        } 
        k++; 
    } 

    // copy remaining elements of left, if any  
    while (i < len1) 
    { 
        arr[k] = left[i]; 
        k++; 
        i++; 
    } 

    // copy remaining element of right, if any  
    while (j < len2)  
    { 
        arr[k] = right[j]; 
        k++; 
        j++; 
    } 
} 

// iterative sort function to sort the  
// array[0...n-1] (similar to merge sort)  
static void sortIntArrayWithComparator(int[] arr, IntComparator comparator) { sortIntArrayWithComparator(arr, lIntArray(arr), comparator); }
static void sortIntArrayWithComparator(int[] arr, int n, IntComparator comparator) { 
    // Sort individual subarrays of size RUN  
    for (int i = 0; i < n; i += sortIntArrayWithComparator_RUN)  
    { 
        sortIntArrayWithComparator_insertionSort(arr, comparator, i, Math.min((i + 31), (n - 1))); 
    } 

    // start merging from size RUN (or 32). It will merge  
    // to form size 64, then 128, 256 and so on ....  
    for (int size = sortIntArrayWithComparator_RUN; size < n; size = 2 * size)  
    { 
          
        // pick starting point of left sub array. We  
        // are going to merge arr[left..left+size-1]  
        // and arr[left+size, left+2*size-1]  
        // After every merge, we increase left by 2*size  
        for (int left = 0; left < n; left += 2 * size)  
        { 
              
            // find ending point of left sub array  
            // mid+1 is starting point of right sub array  
            int mid = Math.min(left + size - 1, n - 1);
            int right = Math.min(left + 2 * size - 1, n - 1); 

            // merge sub array arr[left.....mid] &  
            // arr[mid+1....right]  
            sortIntArrayWithComparator_merge(arr, comparator, left, mid, right); 
        } 
    } 
}

static int lIntArray(int[] a) {
  return a == null ? 0 : a.length;
}

static interface IntComparator {
  int compare(int a, int b);
}

How to update /etc/hosts file in Docker image during "docker build"

Since this still comes up as a first answer in Google I'll contribute possible solution.

Command taken from here suprisingly worked for me (Docker 1.13.1, Ubuntu 16.04) :

docker exec -u 0 <container-name> /bin/sh -c "echo '<ip> <name> >> /etc/hosts"

Getting Serial Port Information

None of the answers here satisfies my needs.

The answer from Muno is wrong because it lists ONLY the USB ports.

The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)

I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.

My code has been tested on Windows XP, Windows 7 and Windows 10.

The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).

If you use my code you do not need SerialPort.GetPortNames() anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??

using System.Management;
using Microsoft.Win32;

using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
    foreach (ManagementObject i_Inst in i_Entity.GetInstances())
    {
        Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
        if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
            continue; // Skip all devices except device class "PORTS"

        String s_Caption  = i_Inst.GetPropertyValue("Caption")     .ToString();
        String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
        String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
        String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
        String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

        int s32_Pos = s_Caption.IndexOf(" (COM");
        if (s32_Pos > 0) // remove COM port from description
            s_Caption = s_Caption.Substring(0, s32_Pos);

        Console.WriteLine("Port Name:    " + s_PortName);
        Console.WriteLine("Description:  " + s_Caption);
        Console.WriteLine("Manufacturer: " + s_Manufact);
        Console.WriteLine("Device ID:    " + s_DeviceID);
        Console.WriteLine("-----------------------------------");
    }
}

I tested the code with a lot of COM ports. This is the Console output:

Port Name:    COM29
Description:  CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID:    USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name:    COM28
Description:  Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID:    USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name:    COM25
Description:  USB-SERIAL CH340
Manufacturer: wch.cn
Device ID:    USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name:    COM26
Description:  Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID:    USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name:    COM1
Description:  Comunications Port
Manufacturer: (Standard port types)
Device ID:    ACPI\PNP0501\1
-----------------------------------
Port Name:    COM999
Description:  EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0000
-----------------------------------
Port Name:    COM20
Description:  EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0001
-----------------------------------
Port Name:    COM8
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name:    COM9
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name:    COM30
Description:  Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID:    USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

COM1 is a COM port on the mainboard.

COM 8 and 9 are Buetooth COM ports.

COM 25 and 26 are USB to RS232 adapters.

COM 28 and 29 and 30 are Arduino-like boards.

COM 20 and 999 are EPSON ports.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

You can redefine/overwrite the default font-awesome sizes and also add you own sizes

.fa-1x{
    font-size:0.8em;
}
.fa-2x{
    font-size:1em;
}
.fa-3x{
    font-size:1.2em;
}
.fa-4x{
    font-size:1.4em;
}
.fa-5x{
    font-size:1.6em;
}
.fa-mycustomx{
    font-size:3.2em;
}

Cannot execute script: Insufficient memory to continue the execution of the program

sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql

  • Open command prompt in run as administrator

  • enter above command

"mamxxxxxmu" is computer name "sqlserverr" is server name "sa" is username of server "x1123" is password of server "QLDB" is database name "D:\qldbscript.sql" is sql script file to execute in database

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Default username password for Tomcat Application Manager

First navigate to below location and open it in a text editor

<TOMCAT_HOME>/conf/tomcat-users.xml

For tomcat 7, Add the following xml code somewhere between <tomcat-users> I find the following solution.

  <role rolename="manager-gui"/>
  <user username="username" password="password" roles="manager-gui"/>

Now restart the tomcat server.

How to bundle vendor scripts separately and require them as needed with Webpack?

in my webpack.config.js (Version 1,2,3) file, I have

function isExternal(module) {
  var context = module.context;

  if (typeof context !== 'string') {
    return false;
  }

  return context.indexOf('node_modules') !== -1;
}

in my plugins array

plugins: [
  new CommonsChunkPlugin({
    name: 'vendors',
    minChunks: function(module) {
      return isExternal(module);
    }
  }),
  // Other plugins
]

Now I have a file that only adds 3rd party libs to one file as required.

If you want get more granular where you separate your vendors and entry point files:

plugins: [
  new CommonsChunkPlugin({
    name: 'common',
    minChunks: function(module, count) {
      return !isExternal(module) && count >= 2; // adjustable
    }
  }),
  new CommonsChunkPlugin({
    name: 'vendors',
    chunks: ['common'],
    // or if you have an key value object for your entries
    // chunks: Object.keys(entry).concat('common')
    minChunks: function(module) {
      return isExternal(module);
    }
  })
]

Note that the order of the plugins matters a lot.

Also, this is going to change in version 4. When that's official, I update this answer.

Update: indexOf search change for windows users

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

Doing Project -> Clean... fixed it for me.

My eclipse had stopped working so I cleaned workspace directory and after I run eclipse when I import the project I had this problem. Other solutions suggested here didn't work.

Using the last-child selector

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Difference between "char" and "String" in Java

A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)

Scraping data from website using vba

There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).

Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.

1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True, but when the code is working for scraping data is nice not to see it everytime so Visible = False.

With appIE
    .Navigate "http://uk.investing.com/rates-bonds/financial-futures"
    .Visible = True
End With

3) The webpage will need some time to load. So, I will wait meanwhile it's busy...

Do While appIE.Busy
    DoEvents
Loop

4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.

enter image description here

5) What I should do is straight-forward. First of all, I will get by the ID property the tr element which is containing the value:

Set allRowOfData = appIE.document.getElementById("pair_8907")

Here I will get a collection of td elements (specifically, tr is a row of data, and the td are its cells. We are looking for the 8th, so I will write:

Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML

Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:

  • .Cells() makes me access the td elements;
  • innerHTML is the property of the cell containing the value we look for.

Once we have our value, which is now stored into the myValue variable, we can just close the IE browser and releasing the memory by setting it to Nothing:

appIE.Quit
Set appIE = Nothing

Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue), or into a label of a form (Me.label1.Text = myValue).

I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.

Enjoy your practice ;)

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

org.hibernate.MappingException: Could not determine type for: java.util.Set

You may just need to add @Transient annotations on roles to not serialize the set.

Why does Java have transient fields?

Magento - Retrieve products with a specific attribute value

create attribute name is "price_screen_tab_name". and access using this simple formula.

<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>

How to get length of a list of lists in python

You can do it with reduce:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

First, create the derived value:

df.loc[0, 'C'] = df.loc[0, 'D']

Then iterate through the remaining rows and fill the calculated values:

for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']


  Index_Date   A   B    C    D
0 2015-01-31  10  10   10   10
1 2015-02-01   2   3   23   22
2 2015-02-02  10  60  290  280

Java switch statement: Constant expression required, but it IS constant

Got this error in Android while doing something like this:

 roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (parent.getItemAtPosition(position)) {
                case ADMIN_CONSTANT: //Threw the error

            }

despite declaring a constant:

public static final String ADMIN_CONSTANT= "Admin";

I resolved the issue by changing my code to this:

roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String selectedItem = String.valueOf(parent.getItemAtPosition(position));
            switch (selectedItem) {
                case ADMIN_CONSTANT:

            }

python pandas remove duplicate columns

Transposing is inefficient for large DataFrames. Here is an alternative:

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []
    for t, v in groups.items():
        dcols = frame[v].to_dict(orient="list")

        vs = dcols.values()
        ks = dcols.keys()
        lvs = len(vs)

        for i in range(lvs):
            for j in range(i+1,lvs):
                if vs[i] == vs[j]: 
                    dups.append(ks[i])
                    break

    return dups       

Use it like this:

dups = duplicate_columns(frame)
frame = frame.drop(dups, axis=1)

Edit

A memory efficient version that treats nans like any other value:

from pandas.core.common import array_equivalent

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []

    for t, v in groups.items():

        cs = frame[v].columns
        vs = frame[v]
        lcs = len(cs)

        for i in range(lcs):
            ia = vs.iloc[:,i].values
            for j in range(i+1, lcs):
                ja = vs.iloc[:,j].values
                if array_equivalent(ia, ja):
                    dups.append(cs[i])
                    break

    return dups

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can just call the Execute command.

EXEC spDoSomthing @myDate

Edit:

Since you want to return data..that's a little harder. You can use user defined functions instead that return data.

Laravel Redirect Back with() Message

In Laravel 5.5:

return back()->withErrors($arrayWithErrors);

In the view using Blade:

@if($errors->has())
    <ul>
    @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

How to copy data to clipboard in C#

Clipboard.SetText("hello");

You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

Turning a Comma Separated string into individual rows

When using this approach you have to make sure that none of your values contains something that would be illegal XML – user1151923

I always use the XML method. Make sure you use VALID XML. I have two functions to convert between valid XML and Text. (I tend to strip out the carriage returns as I don't usually need them.

CREATE FUNCTION dbo.udf_ConvertTextToXML (@Text varchar(MAX)) 
    RETURNS varchar(MAX)
AS
    BEGIN
        SET @Text = REPLACE(@Text,CHAR(10),'')
        SET @Text = REPLACE(@Text,CHAR(13),'')
        SET @Text = REPLACE(@Text,'<','&lt;')
        SET @Text = REPLACE(@Text,'&','&amp;')
        SET @Text = REPLACE(@Text,'>','&gt;')
        SET @Text = REPLACE(@Text,'''','&apos;')
        SET @Text = REPLACE(@Text,'"','&quot;')
    RETURN @Text
END


CREATE FUNCTION dbo.udf_ConvertTextFromXML (@Text VARCHAR(MAX)) 
    RETURNS VARCHAR(max)
AS
    BEGIN
        SET @Text = REPLACE(@Text,'&lt;','<')
        SET @Text = REPLACE(@Text,'&amp;','&')
        SET @Text = REPLACE(@Text,'&gt;','>')
        SET @Text = REPLACE(@Text,'&apos;','''')
        SET @Text = REPLACE(@Text,'&quot;','"')
    RETURN @Text
END

How to shutdown my Jenkins safely?

You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.

What does "#include <iostream>" do?

In order to read or write to the standard input/output streams you need to include it.

int main( int argc, char * argv[] )
{
    std::cout << "Hello World!" << std::endl;
    return 0;
}

That program will not compile unless you add #include <iostream>

The second line isn't necessary

using namespace std;

What that does is tell the compiler that symbol names defined in the std namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example

#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

Notice you no longer need to refer to the output stream with the fully qualified name std::cout and can use the shorter name cout.

I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:

#include <iostream>
using std::cout;
using std::endl;

int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

But that is a matter of personal preference.

javascript variable reference/alias

Expanding on user187291's post, you could also use getters/setters to get around having to use functions.

var x = 1;
var ref = {
    get x()  { return x; },
    set x(v) { x = v; }
};
(ref.x)++;
console.log(x); // prints '2'
x--;
console.log(ref.x); // prints '1'

How to delete migration files in Rails 3

This also works in Rails 5.

If the migration was the most recent one you can remove the database column(s) that the migration added by doing:

rake db:rollback

then remove the migration file itself by running:

rails d migration WhateverYourMigrationWasNamed.rb 

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

ASP.NET MVC3 Razor - Html.ActionLink style

Here's the signature.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

You might want to do this.

@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
     new { @style="text-transform:capitalize;" });

Can you target <br /> with css?

This will work, but only in IE. I tested it in IE8.

br {

  border-bottom: 1px dashed #000000;
  background-color: #ffffff;
  display: block;
  }

this.getClass().getClassLoader().getResource("...") and NullPointerException

One other thing to look at that solved it for me :

In an Eclipse / Maven project, I had Java classes in src/test/java in which I was using the this.getClass().getResource("someFile.ext"); pattern to look for resources in src/test/resources where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.

Right click on the src/test/resources source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext to make sure my files weren't getting scrubbed; my tests now can find their resource files.

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);