Programs & Examples On #Asp.net mvc futures

The futures project contains features that the ASP.NET MVC team is considering for a future release of ASP.NET MVC. Available at http://aspnet.codeplex.com/

JOptionPane - input dialog box program

One solution is to actually use an integer array instead of separate test strings:

You could loop parse the response from JOptionPane.showInputDialog into the individual elements of the array.

Arrays.sort could be used to sort them to allow you to pick out the 2 highest values.

The average can be easily calculated then by adding these 2 values & dividing by 2.

int[] testScore = new int[3];

for (int i = 0; i < testScore.length; i++) {
   testScore[i] = Integer.parseInt(JOptionPane.showInputDialog("Please input mark for test " + i + ": "));
}

Arrays.sort(testScore);
System.out.println("Average: " + (testScore[1] + testScore[2])/2.0);

How to set environment variables in Python?

What about os.environ["DEBUSSY"] = '1'? Environment variables are always strings.

Is mongodb running?

Correct, closing the shell will stop MongoDB. Try using the --fork command line arg for the mongod process which makes it run as a daemon instead. I'm no Unix guru, but I'm sure there must be a way to then get it to auto start when the machine boots up.

e.g.

mongod --fork --logpath /var/log/mongodb.log --logappend

Check out the full documentation on Starting and Stopping Mongo.

How to concatenate int values in java?

Actually,

int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);

will work.

Note: this will only work when a is greater than 0 and all of b, c, d and e are in [0, 9]. For example, if b is 15, Michael's method will get you the result you probably want.

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

How to make a Bootstrap accordion collapse when clicking the header div?

All you need to do is to to use...

  • data-toggle="collapse"
  • data-target="#ElementToExpandOnClick"

...on the element you want to click to trigger the collapse/expand effect.

The element with data-toggle="collapse" will be the element to trigger the effect. The data-target attribute indicates the element that will expand when the effect is triggered.

Optionally you can set the data-parent if you want to create an accordion effect instead of independent collapsible, e.g.:

  • data-parent="#accordion"

I would also add the following CSS to the elements with data-toggle="collapse" if they aren't <a> tags, e.g.:

.panel-heading {
    cursor: pointer;
}

Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.

What are bitwise shift (bit-shift) operators and how do they work?

One gotcha is that the following is implementation dependent (according to the ANSI standard):

char x = -1;
x >> 1;

x can now be 127 (01111111) or still -1 (11111111).

In practice, it's usually the latter.

Does JavaScript pass by reference?

Objects are always pass by reference and primitives by value. Just keep that parameter at the same address for objects.

Here's some code to illustrate what I mean (try it in a JavaScript sandbox such as https://js.do/).

Unfortunately you can't only retain the address of the parameter; you retain all the original member values as well.

a = { key: 'bevmo' };
testRetain(a);
document.write(' after function ');
document.write(a.key);


function testRetain (b)
{
    document.write(' arg0 is ');
    document.write(arguments[0].key);
    b.key = 'passed by reference';
    var retain = b; // Retaining the original address of the parameter

    // Address of left set to address of right, changes address of parameter
    b = {key: 'vons'}; // Right is a new object with a new address
    document.write(' arg0 is ');
    document.write(arguments[0].key);

    // Now retrieve the original address of the parameter for pass by reference
    b = retain;
    document.write(' arg0 is ');
    document.write(arguments[0].key);
}

Result:

arg0 is bevmo arg0 is vons arg0 is passed by reference after function passed by reference

Display an array in a readable/hierarchical format

foreach($array as $v) echo $v, PHP_EOL;

UPDATE: A more sophisticated solution would be:

 $test = [
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => [
        'subkey1' => 'subval1',
        'subkey2' => 'subval2',
        'subkey3' => [
            'subsubkey1' => 'subsubval1',
            'subsubkey2' => 'subsubval2',
        ],
    ],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
    $outerPad = $pad;
    $innerPad = $pad + 1;
    $out = '[' . PHP_EOL;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
        } else {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
            $out .= PHP_EOL;
        }
    }
    $out .= str_repeat($padStr, $outerPad) . ']';
    return $out;
}

echo printArray($test);

This prints out:

    [
        key1 => val1
        key2 => val2
        key3 => [
            subkey1 => subval1
            subkey2 => subval2
            subkey3 => [
                subsubkey1 => subsubval1
                subsubkey2 => subsubval2
            ]
        ]
    ]

How to set dropdown arrow in spinner?

Copy and paste this xml to show as a Dropdown and change your Dropdown color

 <?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp" 
    android:background="@drawable/red">

    <Spinner android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dropDownWidth="fill_parent" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"

     />

</LinearLayout>

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/linearLayout1"
    android:layout_alignRight="@+id/linearLayout1"
    android:layout_below="@+id/linearLayout1"
    android:layout_marginTop="25dp"
    android:background="@drawable/red"
    android:ems="10"
    android:hint="enter card number" >

    <requestFocus />
</EditText>

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignRight="@+id/editText1"
    android:layout_below="@+id/editText1"
    android:layout_marginTop="33dp"
    android:orientation="horizontal" 
    android:background="@drawable/red">

    <Spinner
        android:id="@+id/spinner3"
        android:layout_width="72dp"
        android:layout_height="wrap_content"
         android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
         />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="72dp"
        android:layout_height="wrap_content" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
        />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="22dp"
        android:layout_height="match_parent"
        android:layout_weight="0.18"
        android:ems="10"
        android:hint="enter cvv" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout3"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignRight="@+id/linearLayout2"
    android:layout_below="@+id/linearLayout2"
    android:layout_marginTop="26dp"
    android:orientation="vertical"
    android:background="@drawable/red" >
</LinearLayout>

<Spinner
    android:id="@+id/spinner4"
    android:layout_width="15dp"
    android:layout_height="18dp"
    android:layout_alignBottom="@+id/linearLayout3"
    android:layout_alignLeft="@+id/linearLayout3"
    android:layout_alignRight="@+id/linearLayout3"
    android:layout_alignTop="@+id/linearLayout3"
    android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"/>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/linearLayout3"
    android:layout_marginTop="18dp"
    android:text="Add Amount"
    android:background="@drawable/buttonsty"/>

Removing all unused references from a project in Visual Studio projects

In VB2008, it works this way:

Project>Add References

Then click on the Recent tab where you can see list of references used recently. Locate the one you do not want and delet it. Then you close without adding anything.

send bold & italic text on telegram bot with html

To send bold:

  1. Set the parse_mode to markdown and send *bold*
  2. Set the parse_mode to html and send <b>bold</b>

To send italic:

  1. Set the parse_mode to markdown and send _italic_
  2. Set the parse_mode to html and send <i>italic</i>

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Overall:You persist entity that is violating database rules like as saving entity that has varchar field over 250 chars ,something like that.

In my case it was a squishy problem with TestEntityManager ,because it use HSQL database /in memory database/ and it persist the user but when you try to find it ,it drops the same exception :/

@RunWith(SpringRunner.class)
@ContextConfiguration(classes= Application.class)
@DataJpaTest
@ActiveProfiles("test")
public class UserServicesTests {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private UserRepository userRepository;

@Test
public void oops() {
    User user = new User();
    user.setUsername("Toshko");
    //EMAIL IS REQUIRED:
    //user.setEmail("OPS");
    this.testEntityManager.persist(user);

    //HERE COMES TE EXCEPTION BECAUSE THE EMAIL FIELD IN TE DATABASE IS REQUIRED :
    this.userRepository.findUserByUsername("Toshko");

    System.out.println();
}
}

Need a query that returns every field that contains a specified letter

I'll assume you meant more or less what you said, and you want to find keywords in your table that "contain the letter 'a' and the letter 'b'." Some of the solutions here give the answer to a different question.

To get keywords that contain both the letters 'a' and 'b' in them (as opposed to those that contain either letter), you can use 'ab' as the in the query below:

select
  keyword
from myTable
where not exists (
  select Nums26.i from Nums26
  where Nums26.i <= len(<matchsetstring>) -- or your dialect's equivalent for LEN()
  and keyword not like '%'+substring(<matchsetstring>,Nums26.i,1)+'%' -- adapt SUBSTRING to your dialect
);

The table named "Nums26" should contain a column "i" (indexed for efficiency) that contains each of the values 1 through 26 (or more if you might try to match more than letters). See below. Advice given by others applies with regard to upper/lower case. If your collation is case-sensitive, however, you can't simply specify 'aAbB' here as your , because that would request keywords that contain each of the four characters a, A, b, and B. You might use UPPER and match 'AB', perhaps.

create table nums26 (
  i int primary key
);
insert into nums26 values (1);
insert into nums26 select 1+i from nums26;
insert into nums26 select 2+i from nums26;
insert into nums26 select 4+i from nums26;
insert into nums26 select 8+i from nums26;
insert into nums26 select 16+i from nums26;

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

android.os.NetworkOnMainThreadException with android 4.2

Please make sure that you don't do any network access on UI Thread, instead do it in Async Task

The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because since HoneyComb are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown.

See this

Windows shell command to get the full path to the current directory?

Create a .bat file under System32, let us name it copypath.bat the command to copy current path could be:

echo %cd% | clip

Explanation:

%cd% will give you current path

CLIP

Description:
    Redirects output of command line tools to the Windows clipboard.
    This text output can then be pasted into other programs.

Parameter List:
    /?                  Displays this help message.

Examples:
    DIR | CLIP          Places a copy of the current directory
                        listing into the Windows clipboard.

    CLIP < README.TXT   Places a copy of the text from readme.txt
                        on to the Windows clipboard.

Now copyclip is available from everywhere.

How to delete a record in Django models?

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

Passing parameters to click() & bind() event in jquery?

From where would you get these values? If they're from the button itself, you could just do

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}

Export and Import all MySQL databases at one time

All the answers I see on this question can have problems with the character sets in some databases due to the problem of redirecting the exit of mysqldump to a file within the shell operator >.

To solve this problem you should do the backup with a command like this

mysqldump -u root -p --opt --all-databases -r backup.sql

To do a good BD restore without any problem with character sets. Obviously you can change the default-character-set as you need.

mysql -uroot -p --default-character-set=utf8
mysql> SET names 'utf8';
mysql> SOURCE backup.sql;

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

Javascript: how to validate dates in format MM-DD-YYYY?

what isn't working about it? here's a tested version:

String.prototype.isValidDate = function()   {

    const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    if (!match || match.length !== 4) {
        return false
    }

    const test = new Date(match[3], match[1] - 1, match[2]);

    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true

Dynamically update values of a chartjs chart

You can check instance of Chart by using Chart.instances. This will give you all the charts instances. Now you can iterate on that instances and and change the data, which is present inside config. suppose you have only one chart in your page.

for (var _chartjsindex in Chart.instances) {
/* 
 * Here in the config your actual data and options which you have given at the 
   time of creating chart so no need for changing option only you can change data
*/
 Chart.instances[_chartjsindex].config.data = [];
 // here you can give add your data
 Chart.instances[_chartjsindex].update();
 // update will rewrite your whole chart with new value
 }

How to delete rows in tables that contain foreign keys to other tables

You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.

ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE 

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

Python Requests throwing SSLError

This is similar to @rafael-almeida 's answer, but I want to point out that as of requests 2.11+, there are not 3 values that verify can take, there are actually 4:

  • True: validates against requests's internal trusted CAs.
  • False: bypasses certificate validation completely. (Not recommended)
  • Path to a CA_BUNDLE file. requests will use this to validate the server's certificates.
  • Path to a directory containing public certificate files. requests will use this to validate the server's certificates.

The rest of my answer is about #4, how to use a directory containing certificates to validate:

Obtain the public certificates needed and place them in a directory.

Strictly speaking, you probably "should" use an out-of-band method of obtaining the certificates, but you could also just download them using any browser.

If the server uses a certificate chain, be sure to obtain every single certificate in the chain.

According to the requests documentation, the directory containing the certificates must first be processed with the "rehash" utility (openssl rehash).

(This requires openssl 1.1.1+, and not all Windows openssl implementations support rehash. If openssl rehash won't work for you, you could try running the rehash ruby script at https://github.com/ruby/openssl/blob/master/sample/c_rehash.rb , though I haven't tried this. )

I had some trouble with getting requests to recognize my certificates, but after I used the openssl x509 -outform PEM command to convert the certs to Base64 .pem format, everything worked perfectly.

You can also just do lazy rehashing:

try:
    # As long as the certificates in the certs directory are in the OS's certificate store, `verify=True` is fine.
    return requests.get(url, auth=auth, verify=True)
except requests.exceptions.SSLError:
    subprocess.run(f"openssl rehash -compat -v my_certs_dir", shell=True, check=True)
    return requests.get(url, auth=auth, verify="my_certs_dir")

HTML - how to make an entire DIV a hyperlink?

This is a late answer, but this question appears highly on search results so it's worth answering properly.

Basically, you shouldn't be trying to make a div clickable, but rather make an anchor div-like by giving the <a> tag a display: block CSS attribute.

That way, your HTML remains semantically valid and you can inherit the typical browser behaviours for hyperlinks. It also works even if javascript is disabled / js resources don't load.

jQuery onclick event for <li> tags

You can get the ID, or any other attribute, using jQuery's attrib function.

$('ul.art-vmenu li').attrib('id');

To get the menu text, which is in the t span, you can do this:

$('ul.art-vmenu li').children('span.t').html();

To change the HTML is just as easy:

$('ul.art-vmenu li').children('span.t').html("I'm different");

Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:

$('ul.art-vemnu li span.t').html();

But I'm assuming you've already got the li's, and want to use child() to find something within that element.

How to enumerate a range of numbers starting at 1

enumerate is trivial, and so is re-implementing it to accept a start:

def enumerate(iterable, start = 0):
    n = start
    for i in iterable:
        yield n, i
        n += 1

Note that this doesn't break code using enumerate without start argument. Alternatively, this oneliner may be more elegant and possibly faster, but breaks other uses of enumerate:

enumerate = ((index+1, item) for index, item)

The latter was pure nonsense. @Duncan got the wrapper right.

Unable to create Android Virtual Device

I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.

You get to the SDK Manager through one of two paths. Option 1. Tools > Android > SDK Manager Option 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)

In the pane "SDK Platforms," check the "Show Packages" box to see the system images.

Select the ones you want, click "Apply" and voilà!

enter image description here

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

Test method is inconclusive: Test wasn't run. Error?

I'm using VS2010, NUnit 2.6.3 (although internally ReSharper says it's using 2.6.2?), ReSharper 7.7.1 & NCrunch 2.5.0.12 and was running into the same "...test is inconclusive..." thing with NUnit, but NCrunch said everything was fine. For most of today NUnit & NCrunch were in sync agreeing about which tests were happy and which needed refactoring, then something happened which I still don't understand, and for a while NCrunch said I had failing tests (but stepping through them showed them to pass), then decided they were all working, and NUnit started complaining about all my tests except one with the same message "..test is inconclusive..." which I was again able to single step through to a pass even though NUnit continued to show it as "inconclusive").

I tried several of the suggestions above to no avail, and finally just closed VS2010 & reopened the solution. Voila, now all my tests are happy again, and NCrunch & NUnit are reporting the same results again. Unfortunately I have no idea what changed to cause them to go out of sync, but closing & reopening VS2010 seems to have fixed it.

Maybe someone else will run into this and be able to use this simple (if ultimately unsatisfying since you don't know what the real fix is) solution.

How to obtain the location of cacerts of the default java installation?

In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts

Checking if a variable is an integer in PHP

When the browser sends p in the querystring, it is received as a string, not an int. is_int() will therefore always return false.

Instead try is_numeric() or ctype_digit()

first-child and last-child with IE8

Since :last-child is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child is supported, as it's defined in the CSS2.1 specification.

One possible solution is to simply give the last child a class name and style that class.

Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.

Python: Select subset from list based on index set

Assuming you only have the list of items and a list of true/required indices, this should be the fastest:

property_asel = [ property_a[index] for index in good_indices ]

This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:

good_indices = [ index for index, item in enumerate(good_objects) if item ]

This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.


For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:

list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True

How to check for null/empty/whitespace values with a single test?

you can use

SELECT [column_name] 
FROM [table_name]
WHERE [column_name] LIKE '% %' 
OR [column_name] IS NULL

How to copy a java.util.List into another java.util.List

This is a really nice Java 8 way to do it:

List<String> list2 = list1.stream().collect(Collectors.toList());

Of course the advantage here is that you can filter and skip to only copy of part of the list.

e.g.

//don't copy the first element 
List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());

The thread has exited with code 0 (0x0) with no unhandled exception

Well, an application may have a lot of threads running in parallel. Some are run by you, the coder, some are run by framework classes (espacially if you are in a GUI environnement).

When a thread has finished its task, it exits and stops to exist. There ie nothing alarming in this and you should not care.

What is the Windows equivalent of the diff command?

There's also Powershell (which is part of Windows). It ain't quick but it's flexible, here's the basic command. People have written various cmdlets and scripts for it if you need better formatting.

PS C:\Users\Troll> Compare-Object (gc $file1) (gc $file2)

Not part of Windows, but if you are a developer with Visual Studio, it comes with WinDiff (graphical)

But my personal favorite is BeyondCompare, which costs $30.

Can you use if/else conditions in CSS?

(Yes, old thread. But it turned up on top of a Google-search so others might be interested as well)

I guess the if/else-logic could be done with javascript, which in turn can dynamically load/unload stylesheets. I haven't tested this across browsers etc. but it should work. This will get you started:

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

c# - approach for saving user settings in a WPF application?

Apart from a database, you can also have following options to save user related settings

  1. registry under HKEY_CURRENT_USER

  2. in a file in AppData folder

  3. using Settings file in WPF and by setting its scope as User

Writing a dict to txt file and reading it back?

Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:

>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))

This code dumps to a text file

$ cat text.txt 
{"two": 2, "one": 1}

Also you can load from a JSON file:

>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

how to make a specific text on TextView BOLD

This is the Kotlin extension function I use for this

/**
 * Sets the specified Typeface Style on the first instance of the specified substring(s)
 * @param one or more [Pair] of [String] and [Typeface] style (e.g. BOLD, ITALIC, etc.)
 */
fun TextView.setSubstringTypeface(vararg textsToStyle: Pair<String, Int>) {
    val spannableString = SpannableString(this.text)
    for (textToStyle in textsToStyle) {
        val startIndex = this.text.toString().indexOf(textToStyle.first)
        val endIndex = startIndex + textToStyle.first.length

        if (startIndex >= 0) {
            spannableString.setSpan(
                StyleSpan(textToStyle.second),
                startIndex,
                endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
    }
    this.setText(spannableString, TextView.BufferType.SPANNABLE)
}

Usage:

text_view.text="something bold"
text_view.setSubstringTypeface(
    Pair(
        "something bold",
        Typeface.BOLD
    )
)

.

text_view.text="something bold something italic"
text_view.setSubstringTypeface(
    Pair(
        "something bold ",
        Typeface.BOLD
    ),
    Pair(
        "something italic",
        Typeface.ITALIC
    )
)

Getting the application's directory from a WPF application

I used simply string baseDir = Environment.CurrentDirectory; and its work for me.

Good Luck

Edit:

I used to delete this type of mistake but i prefer to edit it because i think the minus point on this answer help people to know about wrong way. :) I understood the above solution is not useful and i changed it to string appBaseDir = System.AppDomain.CurrentDomain.BaseDirectory; Other ways to get it are:

1. string baseDir =   
    System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
 2. String exePath = System.Environment.GetCommandLineArgs()[0];
 3. string appBaseDir =    System.IO.Path.GetDirectoryName
    (System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

Good Luck

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Where is database .bak file saved from SQL Server Management Studio?

...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

I'm not absolutely sure I got your question correctly, but it seems you want something like this:

    Class c = null;
    try {
        c = Class.forName("com.path.to.ImplementationType");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    T interfaceType = null;
    try {
        interfaceType = (T) c.newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

Where T can be defined in method level or in class level, i.e. <T extends InterfaceType>

How to start anonymous thread class

Add: now you can use lambda to simplify your syntax. Requirement: Java 8+

public class A {
    public static void main(String[] arg)
    {
        Thread th = new Thread(() -> {System.out.println("blah");});
        th.start();
    }
}

How to run a stored procedure in oracle sql developer?

Try to execute the procedure like this,

var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;

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

From Wikipedia:

UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.

So this is my code:

TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;

Can you use a trailing comma in a JSON object?

Trailing commas are allowed in JavaScript, but don't work in IE. Douglas Crockford's versionless JSON spec didn't allow them, and because it was versionless this wasn't supposed to change. The ES5 JSON spec allowed them as an extension, but Crockford's RFC 4627 didn't, and ES5 reverted to disallowing them. Firefox followed suit. Internet Explorer is why we can't have nice things.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

In many cases some antivirus also start HyperV with window start and does not allow HAXM to install. I faced this issue because of AVAST antivirus. So I uninstalled AVAST, then HAXM installed properly after restart. Then I re-installed AVAST.

So its just a check while installing as now even with AVAST installed back, HAXM works properly with virtual box and android emulators.

Change event on select with knockout binding, how can I know if it is a real change?

Try this one:

self.GetHierarchyNodeList = function (data, index, event)
{
    debugger;
    if (event.type != "change") {
        return;
    }        
} 

event.type == "change"
event.type == "load" 

How to capture the "virtual keyboard show/hide" event in Android?

Like @amalBit's answer, register a listener to global layout and calculate the difference of dectorView's visible bottom and its proposed bottom, if the difference is bigger than some value(guessed IME's height), we think IME is up:

    final EditText edit = (EditText) findViewById(R.id.edittext);
    edit.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (keyboardShown(edit.getRootView())) {
                Log.d("keyboard", "keyboard UP");
            } else {
                Log.d("keyboard", "keyboard Down");
            }
        }
    });

private boolean keyboardShown(View rootView) {

    final int softKeyboardHeight = 100;
    Rect r = new Rect();
    rootView.getWindowVisibleDisplayFrame(r);
    DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
    int heightDiff = rootView.getBottom() - r.bottom;
    return heightDiff > softKeyboardHeight * dm.density;
}

the height threshold 100 is the guessed minimum height of IME.

This works for both adjustPan and adjustResize.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

Add User to Role ASP.NET Identity

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The problem seems to be that block elements only scale up to 100% of their containing element, no matter how big their content is—it just overflows. However, making them inline-block elements apparently resizes their width to their actual content.

HTML:

<div id="container">
    <div class="wide">
        foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
    </div>
    <div class="wide">
        bar
    </div>
</div>

CSS:

.wide { min-width: 100%; display: inline-block; background-color: yellow; }
#container { display: inline-block; }

(The containerelement addresses your follow-up question to make the second div as big as the previous one, and not just the screen width.)

I also set up a JS fiddle showing my demo code.

If you run into any troubles (esp. cross-browser issues) with inline-block, looking at Block-level elements within display: inline-block might help.

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

It looks like the original answer was for pre Apache 2.4. It did not work for me. Here's what I had to change to make it work in 2.4. This will work for any depth of subdomain of yourcompany.com.

SetEnvIf Host ^((?:.+\.)*yourcompany\.com?)$    CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{REQUEST_SCHEME}e://%{CORS_ALLOW_ORIGIN}e    env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

Load JSON text into class object in c#

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques enter image description here

What does <T> denote in C#

It is a Generic Type Parameter.

A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

For example:

public T[] Reverse<T>(T[] array)
{
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.

So, to reverse an array of strings:

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

Will produce a string array in result of { "5", "4", "3", "2", "1" }

This has the same effect as if you had called an ordinary (non-generic) method that looks like this:

public string[] Reverse(string[] array)
{
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.


Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.

So:

var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

SQL Server equivalent to MySQL enum data type?

IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4

Have Fun!

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

How to calculate modulus of large numbers?

5^55 mod221

= (   5^10         * 5^10         * 5^10         * 5^10          * 5^10          * 5^5) mod221    

= ( ( 5^10) mod221 * 5^10         * 5^10         * 5^10          * 5^10          * 5^5) mod221 

= (   77           * 5^10         * 5^10         * 5^10          * 5^10          * 5^5) mod221   

= ( ( 77           * 5^10) mod221 * 5^10         * 5^10          * 5^10          * 5^5) mod221 

= (   183                         * 5^10         * 5^10          * 5^10          * 5^5) mod221 

= ( ( 183                         * 5^10) mod221 * 5^10          * 5^10          * 5^5) mod221 

= (   168                                        * 5^10          * 5^10          * 5^5) mod221 

= ( ( 168                                        * 5^10) mod 221 * 5^10          * 5^5) mod221 

= (   118                                                        * 5^10          * 5^5) mod221 

= ( ( 118                                                        * 5^10) mod 221 * 5^5) mod221 

= (   25                                                                         * 5^5) mod221 

=     112

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

Bootstrap: change background color

You can target that div from your stylesheet in a number of ways.

Simply use

.col-md-6:first-child {
  background-color: blue;
}

Another way is to assign a class to one div and then apply the style to that class.

<div class="col-md-6 blue"></div>

.blue {
  background-color: blue;
}

There are also inline styles.

<div class="col-md-6" style="background-color: blue"></div>

Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

_x000D_
_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
    <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
      <div class="col-xs-6">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
      <div class="col-xs-6 blue">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Why is @font-face throwing a 404 error on woff files?

I was experiencing this same symptom - 404 on woff files in Chrome - and was running an application on a Windows Server with IIS 6.

If you are in the same situation you can fix it by doing the following:

Solution 1

"Simply add the following MIME type declarations via IIS Manager (HTTP Headers tab of website properties): .woff application/x-woff"

Update: according to MIME Types for woff fonts and Grsmto the actual MIME type is application/x-font-woff (for Chrome at least). x-woff will fix Chrome 404s, x-font-woff will fix Chrome warnings.

As of 2017: Woff fonts have now been standardised as part of the RFC8081 specification to the mime type font/woff and font/woff2.

IIS 6 MIME Types

Thanks to Seb Duggan: http://sebduggan.com/posts/serving-web-fonts-from-iis

Solution 2

You can also add the MIME types in the web config:

  <system.webServer>
    <staticContent>
      <remove fileExtension=".woff" /> <!-- In case IIS already has this mime type -->
      <mimeMap fileExtension=".woff" mimeType="font/woff" />
    </staticContent>    
  </system.webServer>

Can I make 'git diff' only the line numbers AND changed file names?

Note: if you're just looking for the names of changed files (without the line numbers for lines that were changed), that's easy, click this link to another answer here.


There's no built-in option for this (and I don't think it's all that useful either), but it is possible to do this in git, with the help of an "external diff" script.

Here's a pretty crappy one; it will be up to you to fix up the output the way you would like it.

#! /bin/sh
#
# run this with:
#    GIT_EXTERNAL_DIFF=<name of script> git diff ...
#
case $# in
1) "unmerged file $@, can't show you line numbers"; exit 1;;
7) ;;
*) echo "I don't know what to do, help!"; exit 1;;
esac

path=$1
old_file=$2
old_hex=$3
old_mode=$4
new_file=$5
new_hex=$6
new_mode=$7

printf '%s: ' $path
diff $old_file $new_file | grep -v '^[<>-]'

For details on "external diff" see the description of GIT_EXTERNAL_DIFF in the git manual page (around line 700, pretty close to the end).

How can I send an email through the UNIX mailx command?

mailx -s "subjec_of_mail" [email protected] < file_name

through mailx utility we can send a file from unix to mail server. here in above code we can see first parameter is -s "subject of mail" the second parameter is mail ID and the last parameter is name of file which we want to attach

How to set Status Bar Style in Swift 3

You need to add below key in your Info.plist file:

View controller-based status bar appearance with boolean value set to NO

In your appdelegate class, in didFinishLaunchingWithOptions method before return.

let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
    statusBar.backgroundColor = UIColor.red
}
UIApplication.shared.statusBarStyle = .lightContent

change backgroundColor and statusBarStyle as per requirement.

How to compare two dates in php

compare the result of maketime() for each of the time

Android Device not recognized by adb

I also faced the same problem and tried almost everything possible from manually installing drivers to editing the winusb.inf file. But nothing worked for me.

Actually, the solution is quite simple. Its always there but we tend to miss it.

Prerequisites

Download the latest Android SDK and the latest drivers from here. Enable USB debugging and open Device Manager and keep it opened.

Steps

1) Connect your device and see if it is detected under "Android Devices" section. If it does, then its OK, otherwise, check the "Other devices" section and install the driver manually.

2) Be sure to check "Android Composite ADB Interface". This is the interface Android needs for ADB to work.

3) Go to "[SDK]/platform-tools", Shift-click there and open Command Prompt and type "adb devices" and see if your device is listed there with an unique ID.

4) If yes, then ADB have been successfully detected at this point. Next, write "adb reboot bootloader" to open the bootloader. At this point check Device Manager under "Android Devices", you will find "Android Bootlaoder Interface". Its not much important to us actually.

5) Next, using the volume down keys, move to "Recovery Mode".

6) THIS IS IMPORTANT - At this point, check the Device Manger under "Android Devices". If you do not see anything under this section or this section at all, then we need to manually install it.

7) Check the "Other devices" section and find your device listed there. Right click -> Update drivers -"Browse my computer..." -> "Let me pick from a list..." and select "ADB Composite Interface".

8) Now you can see your device listed under "Android Devices" even inside the Recovery.

9) Write "adb devices" at this point and you will see your device listed with the same ID.

10) Now, just write "adb sideload [update].zip" and your are done.

Hope this helps.

Unresponsive KeyListener for JFrame

InputMaps and ActionMaps were designed to capture the key events for the component, it and all of its sub-components, or the entire window. This is controlled through the parameter in JComponent.getInputMap(). See How to Use Key Bindings for documentation.

The beauty of this design is that one can pick and choose which key strokes are important to monitor and have different actions fired based on those key strokes.

This code will call dispose() on a JFrame when the escape key is hit anywhere in the window. JFrame doesn't derive from JComponent so you have to use another component in the JFrame to create the key binding. The content pane might be such a component.

InputMap inputMap; 
ActionMap actionMap;
AbstractAction action;
JComponent component;

inputMap  = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
actionMap = component.getActionMap();

action    = new AbstractAction()
{
   @Override
   public void actionPerformed(ActionEvent e)
   {
      dispose();
   }
};

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dispose");
actionMap.put("dispose", action);

Understanding ibeacon distancing

With multiple phones and beacons at the same location, it's going to be difficult to measure proximity with any high degree of accuracy. Try using the Android "b and l bluetooth le scanner" app, to visualize the signal strengths (distance) variations, for multiple beacons, and you'll quickly discover that complex, adaptive algorithms may be required to provide any form of consistent proximity measurement.

You're going to see lots of solutions simply instructing the user to "please hold your phone here", to reduce customer frustration.

Convert an array to string

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

Python: Fetch first 10 results from a list

list[:10]

will give you the first 10 elements of this list using slicing.

However, note, it's best not to use list as a variable identifier as it's already used by Python: list()

To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)

How to Find App Pool Recycles in Event Log

As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer


It is definitely System Log.

Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx.

You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.

You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.

How to import jquery using ES6 syntax?

import {jQuery as $} from 'jquery';

Why use the INCLUDE clause when creating an index?

One reason to prefer INCLUDE over key-columns if you don't need that column in the key is documentation. That makes evolving indexes much more easy in the future.

Considering your example:

CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)

That index is best if your query looks like this:

SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...

Of course you should not put columns in INCLUDE if you can get an additional benefit from having them in the key part. Both of the following queries would actually prefer the col2 column in the key of the index.

SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...
   AND col2 = ...
SELECT TOP 1 col2, col3
  FROM MyTable
 WHERE col1 = ...
 ORDER BY col2

Let's assume this is not the case and we have col2 in the INCLUDE clause because there is just no benefit of having it in the tree part of the index.

Fast forward some years.

You need to tune this query:

SELECT TOP 1 col2
  FROM MyTable
 WHERE col1 = ...
 ORDER BY another_col

To optimize that query, the following index would be great:

CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2)

If you check what indexes you have on that table already, your previous index might still be there:

CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)

Now you know that Col2 and Col3 are not part of the index tree and are thus not used to narrow the read index range nor for ordering the rows. Is is rather safe to add another_column to the end of the key-part of the index (after col1). There is little risk to break anything:

DROP INDEX idx1 ON MyTable;
CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2, Col3);

That index will become bigger, which still has some risks, but it is generally better to extend existing indexes compared to introducing new ones.

If you would have an index without INCLUDE, you could not know what queries you would break by adding another_col right after Col1.

CREATE INDEX idx1 ON MyTable (Col1, Col2, Col3)

What happens if you add another_col between Col1 and Col2? Will other queries suffer?

There are other "benefits" of INCLUDE vs. key columns if you add those columns just to avoid fetching them from the table. However, I consider the documentation aspect the most important one.

To answer your question:

what guidelines would you suggest in determining whether to create a covering index with or without the INCLUDE clause?

If you add a column to the index for the sole purpose to have that column available in the index without visiting the table, put it into the INCLUDE clause.

If adding the column to the index key brings additional benefits (e.g. for order by or because it can narrow the read index range) add it to the key.

You can read a longer discussion about this here:

https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes

Eclipse cannot load SWT libraries

If you start eclipse using oracle java, then eclipse might fail in finding native libraries like SWT or SVN libraries. The SWT-JNI libraries are located in /usr/lib/jni/ and the SVN-JNI libraries are located in /usr/lib/x86_64-linux-gnu/jni/.

Instead of starting eclipse with the command

eclipse

you can use the command

env LD_LIBRARY_PATH=/usr/lib/jni/:/usr/lib/x86_64-linux-gnu/jni/:$LD_LIBRARY_PATH eclipse

to pass the environment variable LD_LIBRARY_PATH to eclipse. Eclipse will find the native libraries and will run properly.

Create an enum with string values

You can use string enums in the latest TypeScript:

enum e
{
    hello = <any>"hello",
    world = <any>"world"
};

Source: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/


UPDATE - 2016

A slightly more robust way of making a set of strings that I use for React these days is like this:

export class Messages
{
    static CouldNotValidateRequest: string = 'There was an error validating the request';
    static PasswordMustNotBeBlank: string = 'Password must not be blank';   
}

import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

KeyListener, keyPressed versus keyTyped

You should use keyPressed if you want an immediate effect, and keyReleased if you want the effect after you release the key. You cannot use keyTyped because F5 is not a character. keyTyped is activated only when an character is pressed.

Horizontal line using HTML/CSS

I have try this my new code and it might be helpful to you, it works perfectly in google chromr

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

My Application Could not open ServletContext resource

Quote from the Spring reference doc:

Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...

Your servlet is called spring-dispatcher, so it looks for /WEB-INF/spring-dispatcher-servlet.xml. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml in your case).

One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

How long do browsers cache HTTP 301s?

In the absense of cache control directives that specify otherwise, a 301 redirect defaults to being cached without any expiry date.

That is, it will remain cached for as long as the browser's cache can accommodate it. It will be removed from the cache if you manually clear the cache, or if the cache entries are purged to make room for new ones.

You can verify this at least in Firefox by going to about:cache and finding it under disk cache. It works this way in other browsers including Chrome and the Chromium based Edge, though they don't have an about:cache for inspecting the cache.

In all browsers it is still possible to override this default behavior using caching directives, as described below:

If you don't want the redirect to be cached

This indefinite caching is only the default caching by these browsers in the absence of headers that specify otherwise. The logic is that you are specifying a "permanent" redirect and not giving them any other caching instructions, so they'll treat it as if you wanted it indefinitely cached.

The browsers still honor the Cache-Control and Expires headers like with any other response, if they are specified.

You can add headers such as Cache-Control: max-age=3600 or Expires: Thu, 01 Dec 2014 16:00:00 GMT to your 301 redirects. You could even add Cache-Control: no-cache so it won't be cached permanently by the browser or Cache-Control: no-store so it can't even be stored in temporary storage by the browser.

Though, if you don't want your redirect to be permanent, it may be a better option to use a 302 or 307 redirect. Issuing a 301 redirect but marking it as non-cacheable is going against the spirit of what a 301 redirect is for, even though it is technically valid. YMMV, and you may find edge cases where it makes sense for a "permanent" redirect to have a time limit. Note that 302 and 307 redirects aren't cached by default by browsers.

If you previously issued a 301 redirect but want to un-do that

If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:

  • A simple solution is to issue another redirect back again.

    If the browser is directed back to a same URL a second time during a redirect, it should fetch it from the origin again instead of redirecting again from cache, in an attempt to avoid a redirect loop. Comments on this answer indicate this now works in all major browsers - but there may be some minor browsers where it doesn't.

  • If you don't have control over the site where the previous redirect target went to, then you are out of luck. Try and beg the site owner to redirect back to you.

Prevention is better than cure - avoid a 301 redirect if you are not sure you want to permanently de-commission the old URL.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

angularjs - ng-repeat: access key and value from JSON array object

try this..

<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

ruby LoadError: cannot load such file

The problem shall have solved if you specify your path.

e.g.

"require 'st.rb'" --> "require './st.rb'"

See if your problem get solved or not.

Get selected option from select element

Given this HTML:

<select>
    <option value="0">One</option>
    <option value="1">Two</option>
</select>

Select by description for jQuery v1.6+:

var text1 = 'Two';
$("select option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == text1; 
}).prop('selected', true);

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

If you are using Windows try out the following:

  1. Press (Windows+R)
  2. enter "services.msc" and click "OK"
  3. locate service with name 'wampapache'

and check if it's status is 'Running'. In case not, right click >> start.

Hope this helps!


If you have removed WAMP from boot services, it won't work – try the following:

  • Press (Windows+R)
  • enter "services.msc" and click "OK"
  • locate service with name 'wampapache'
  • Right click wampapache and wampmysqld, Click 'properties'
  • and change Start Type to Manual or automatic

This will work!

showDialog deprecated. What's the alternative?

To display dialog box, you can use the following code. This is to display a simple AlertDialog box with multiple check boxes:

AlertDialog.Builder alertDialog= new AlertDialog.Builder(MainActivity.this); .
            alertDialog.setTitle("this is a dialog box ");
            alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(),"ok ive wrote this 'ok' here" ,Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                        Toast.makeText(getBaseContext(), "cancel ' comment same as ok'", Toast.LENGTH_SHORT).show();


                }
            });
            alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(), items[which] +(isChecked?"clicked'again i've wrrten this click'":"unchecked"),Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.show();

Heading

Whereas if you are using the showDialog function to display different dialog box or anything as per the arguments passed, you can create a self function and can call it under the onClickListener() function. Something like:

 public CharSequence[] items={"google","Apple","Kaye"};
public boolean[] checkedItems=new boolean[items.length];
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt=(Button) findViewById(R.id.bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            display(0);             
        }       
    });
}

and add the code of dialog box given above in the function definition.

How to split a string literal across multiple lines in C / Objective-C?

You could also go into XCode -> Preferences, select the Indentation tab, and turn on Line Wrapping.

That way, you won't have to type anything extra, and it will work for the stuff you already wrote. :-)

One annoying thing though is...

if (you're long on indentation
    && short on windows) {
            then your code will
                end up squished
                     against th
                         e side
                             li
                              k
                              e

                              t
                              h
                              i
                              s
}

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

Reminder - \r\n or \n\r?

New line depends on your OS:

DOS & Windows: \r\n 0D0A (hex), 13,10 (decimal)
Unix & Mac OS X: \n, 0A, 10
Macintosh (OS 9): \r, 0D, 13

More details here: https://ccrma.stanford.edu/~craig/utility/flip/

When in doubt, use any freeware hex viewer/editor to see how a file encodes its new line.

For me, I use following guide to help me remember: 0D0A = \r\n = CR,LF = carriage return, line feed

python .replace() regex

In order to replace text using regular expression use the re.sub function:

sub(pattern, repl, string[, count, flags])

It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.

Examples

>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'

>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

Git undo changes in some files

There are three basic ways to do this depending on what you have done with the changes to the file A. If you have not yet added the changes to the index or committed them, then you just want to use the checkout command - this will change the state of the working copy to match the repository:

git checkout A

If you added it to the index already, use reset:

git reset A

If you had committed it, then you use the revert command:

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

If on the other hand, you had committed it, but the commit involved rather a lot of files that you do not also want to revert, then the above method might involve a lot of "reset B" commands. In this case, you might like to use this method:

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

Another method again, requires the use of the rebase -i command. This one can be useful if you have more than one commit to edit:

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue

Get SSID when WIFI is connected

Android 9 SSID showing NULL values use this code..

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = wifiInfo.getSSID();
            return ssid.replaceAll("^\"|\"$", "");
        }

How to install requests module in Python 3.4, instead of 2.7

Just answering this old thread can be installed without pip On windows or Linux:

1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button

2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there

3) Depending on the Os run the following command:

  • Windows use command cd to your python directory location then setup.py install
  • Linux command: python setup.py install

Thats it :)

moment.js 24h format

_x000D_
_x000D_
//Format 24H use HH:mm_x000D_
let currentDate = moment().format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDate)_x000D_
_x000D_
//example of current time with defined Time zone +1_x000D_
let currentDateTm = moment().utcOffset('+0100').format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDateTm)
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Git: How to reset a remote Git repository to remove all commits?

Completely reset?

  1. Delete the .git directory locally.

  2. Recreate the git repostory:

    $ cd (project-directory)
    $ git init
    $ (add some files)
    $ git add .
    $ git commit -m 'Initial commit'
    
  3. Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.

    $ git remote add origin <url>
    $ git push --force --set-upstream origin master
    

Check if DataRow exists by column name in c#?

if (drMyRow.Table.Columns["ColNameToCheck"] != null)
{
   doSomethingUseful;
{
else { return; }

Although the DataRow does not have a Columns property, it does have a Table that the column can be checked for.

Error on renaming database in SQL Server 2008 R2

use master

ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE  

exec sp_renamedb 'BOSEVIKRAM','BOSEVIKRAM_Deleted'

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

I had the same problem, where my Action Bar would turn grey when I entered that code. Chances are your original style sheet looked like this:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- API 14 theme customizations can go here. -->
</style>

The "DarkActionBar" was what was keeping your Action Bar grey. I changed it to this, and it worked:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    <!-- API 14 theme customizations can go here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#2aa4cd</item>
    <item name="android:titleTextStyle">@style/Theme.MyAppTheme.ActionBar.TitleTextStyle</item>
</style>        

<style name="Theme.MyAppTheme.ActionBar.TitleTextStyle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">#FFFFFF</item>
</style>    

I also threw in how to edit the text color. Also, no need to change anything surrounding the resources.

-Warren

Check if application is on its first run

The following is an example of using SharedPreferences to achieve a 'first run' check.

public class MyActivity extends Activity {

    SharedPreferences prefs = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Perhaps set content view here

        prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (prefs.getBoolean("firstrun", true)) {
            // Do first run stuff here then set 'firstrun' as false
            // using the following line to edit/commit prefs
            prefs.edit().putBoolean("firstrun", false).commit();
        }
    }
}

When the code runs prefs.getBoolean(...) if there isn't a boolean saved in SharedPreferences with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit(); will have been executed and therefore prefs.getBoolean("firstrun", true) will actually return false as it overrides the default true provided as the second parameter.

When do I use path params vs. query params in a RESTful API?

In a REST API, you shouldn't be overly concerned by predictable URI's. The very suggestion of URI predictability alludes to a misunderstanding of RESTful architecture. It assumes that a client should be constructing URIs themselves, which they really shouldn't have to.

However, I assume that you are not creating a true REST API, but a 'REST inspired' API (such as the Google Drive one). In these cases the rule of thumb is 'path params = resource identification' and 'query params = resource sorting'. So, the question becomes, can you uniquely identify your resource WITHOUT status / region? If yes, then perhaps its a query param. If no, then its a path param.

HTH.

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

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

if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command

adb install apklocation.apk

Identifier not found error on function call

At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:

void swapCase(char* name);

Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write

if ('A' <= name[i] && name[i] <= 'Z')
    name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
    name[i] += 'A' - 'a';

The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.

Good luck learning!

How to change the port of Tomcat from 8080 to 80?

Running the command below worked with. Tried changing server.xml and the conf file but both didn't work.

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT

/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Selecting multiple columns in a Pandas dataframe

I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?

The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.

Example

print(extracted_features.shape)
print(extracted_features)

(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
 'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
 'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
 'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
 'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
 'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
 'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
 'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
 'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']

I have the following list/NumPy array extracted_features, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use

dataset[extracted_features]

And you will end up with this

Enter image description here

This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.

Easy pretty printing of floats in python?

l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]

Python 2:

print ', '.join('{:0.2f}'.format(i) for i in l)

Python 3:

print(', '.join('{:0.2f}'.format(i) for i in l))

Output:

9.00, 0.05, 0.03, 0.01, 0.06, 0.08

How can I check if an array contains a specific value in php?

From http://php.net/manual/en/function.in-array.php

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

How to use CSS to surround a number with a circle?

enter image description here

Here's a demo on JSFiddle and a snippet:

_x000D_
_x000D_
/* Creating a number within a circle using CSS */
_x000D_
.numberCircle {
    font-family: "OpenSans-Semibold", Arial, "Helvetica Neue", Helvetica, sans-serif;
    display: inline-block;
    color: #fff;
    text-align: center;
    line-height: 0px;
    border-radius: 50%;
    font-size: 12px;
    min-width: 38px;
    min-height: 38px;
}

.numberCircle span {
    display: inline-block;
    padding-top: 50%;
    padding-bottom: 50%;
    margin-left: 1px;
    margin-right: 1px;
}

/* Some Back Ground Colors */
.clrGreen {
    background: #51a529;
}
.clrRose {
    background: #e6568b;
}
.clrOrange {
    background: #ec8234;
}
.clrBlueciel {
    background: #21adfc;
}
.clrMauve {
    background: #7b5d99;
}
_x000D_
<span class="numberCircle clrGreen"><span>8</span></span>
<span class="numberCircle clrRose"><span>80</span></span>
<span class="numberCircle clrOrange"><span>800</span></span>
<span class="numberCircle clrMauve"><span>8000</span></span>
_x000D_
_x000D_
_x000D_

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to refresh an IFrame using Javascript?

If you have Multiple iFrames inside the page, then this script might be useful. I am asuming there is a specific value in the iFrame source which can be used to find the specific iFrame.

var iframes = document.getElementsByTagName('iframe');
var yourIframe = null
for(var i=0; i < iframes.length ;i++){
    var source =  iframes[i].attributes.src.nodeValue;
    if(source.indexOf('/yourSorce') > -1){
        yourIframe = iframes[i];
    }   
}
var iSource = yourIframe.attributes.src.nodeValue;
yourIframe.src = iSource;

Replace "/yourSource" with value you need.

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

How to create a jQuery function (a new jQuery method or plugin)?

It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function ($(selector/DOM element)) would have this method.

Here is a very simple example:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

What's the difference between all the Selection Segues?

Here is a quick summary of the segues and an example for each type.

Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail

Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout

Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings

Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar

Custom - You may implement your own custom segue and have control over its behavior

The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.

For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.

add string to String array

First, this code here,

string [] scripts = new String [] ("test3","test4","test5");

should be

String[] scripts = new String [] {"test3","test4","test5"};

Please read this tutorial on Arrays

Second,

Arrays are fixed size, so you can't add new Strings to above array. You may override existing values

scripts[0] = string1;

(or)

Create array with size then keep on adding elements till it is full.

If you want resizable arrays, consider using ArrayList.

Command not found when using sudo

Ok this is my solution: in ~/.bash_aliases just add the following:

# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
   export PATH=$PATH:/home/your_user/bin 
fi

Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.

Notice that I need to be explicit when adding my PATH since HOME for superuser is /root

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

Set default value of javascript object attributes

I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?

How can I store and retrieve images from a MySQL database using PHP?

My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database. As we compare both options, Storing images in the database is safe for security purpose. Disadvantage are

  1. If database is corrupted, no way to retrieve.

  2. Retrieving image files from db is slow when compare to other option.

On the other hand, storing image file location in db will have following advantages.

  1. It is easy to retrieve.

  2. If more than one images are stored, we can easily retrieve image information.

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Does Internet Explorer 8 support HTML 5?

HTML5 is still in draft spec (and will be for a loooong time). Why bother?

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Coming here from first Google hit:

You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1.

On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1 the warning will go away.

It's probably because you are building a gem from source and the gemspec shells out to git, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git but addressing that is for another day :)

My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Why doesn't calling a Python string method do anything unless you assign its output?

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

What are CN, OU, DC in an LDAP search?

At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):

"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"

Gradle finds wrong JAVA_HOME even though it's correctly set

Try installing latest version of gradle,

sudo add-apt-repository ppa:cwchien/gradle

sudo apt-get update

sudo apt-get install gradle

If we install from ubuntu repo, it will install the old version , (for me it was gradle 1.4). In older version, it sets java home from gradle as export JAVA_HOME=/usr/lib/jvm/default-java. Latest version don't have this issue.

How do you use the "WITH" clause in MySQL?

I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

Which produces:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

How to clear input buffer in C?

Try this:

stdin->_IO_read_ptr = stdin->_IO_read_end;

How to avoid warning when introducing NAs by coercion

suppressWarnings() has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.

> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion 
> y <- destring(c("1", "2", "X"))
> y
[1]  1  2 NA
> x
[1]  1  2 NA

Converting pfx to pem using openssl

Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):

First case: To convert a PFX file to a PEM file that contains both the certificate and private key:

openssl pkcs12 -in filename.pfx -out cert.pem -nodes

Second case: To convert a PFX file to separate public and private key PEM files:

Extracts the private key form a PFX to a PEM file:

openssl pkcs12 -in filename.pfx -nocerts -out key.pem

Exports the certificate (includes the public key only):

openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem

Removes the password (paraphrase) from the extracted private key (optional):

openssl rsa -in key.pem -out server.key

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

What does body-parser do with express?

Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.

Or you can use body-parser, as the express team is maintaining it .

What body-parser can do for you: It simplifies the request.
How to use it: Here is example:

Install npm install body-parser --save

This how to use body-parser in express:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

Link.

https://github.com/expressjs/body-parser.

And then you can get body and headers in root request object . Example

app.post("/posturl",function(req,res,next){
    console.log(req.body);
    res.send("response");
})

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

How to add a class with React.js?

this is pretty useful:

https://github.com/JedWatson/classnames

You can do stuff like

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

or use it like this

var btnClass = classNames('btn', this.props.className, {
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

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

Try this way :

<a href="{{ URL::to('/registration') }}">registration </a>

How to modify existing, unpushed commit messages?

As already mentioned, git commit --amend is the way to overwrite the last commit. One note: if you would like to also overwrite the files, the command would be

git commit -a --amend -m "My new commit message"

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

How to enumerate an enum with String type?

EDIT: Swift Evolution Proposal SE-0194 Derived Collection of Enum Cases proposes a level headed solution to this problem. We see it in Swift 4.2 and newer. The proposal also points out to some workarounds that are similar to some already mentioned here but it might be interesting to see nevertheless.

I will also keep my original post for completeness' sake.


This is yet another approach based on @Peymmankh's answer, adapted to Swift 3.

public protocol EnumCollection: Hashable {}

extension EnumCollection {

public static func allValues() -> [Self] {
    typealias S = Self

    let retVal = AnySequence { () -> AnyIterator<S> in
        var raw = 0
        return AnyIterator {
            let current = withUnsafePointer(to: &raw) {
                 $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee }
            }
            guard current.hashValue == raw else { return nil }
            raw += 1
            return current
        }
    }

    return [S](retVal)
}

How do I jump out of a foreach loop in C#?

var ind=0;
foreach(string s in sList){
    if(s.equals("ok")){
        return true;
    }
    ind++;
}
if (ind==sList.length){
    return false;
}

How to set "style=display:none;" using jQuery's attr method?

Please try below code for it :

$('#msform').fadeOut(50);

$('#msform').fadeIn(50);

Remove trailing zeros from decimal in SQL Server

Another option...

I don't know how efficient this is but it seems to work and does not go via float:

select replace(rtrim(replace(
       replace(rtrim(replace(cast(@value as varchar(40)), '0', ' ')), ' ', '0')
       , '.', ' ')), ' ', '.')

The middle line strips off trailing spaces, the outer two remove the point if there are no decimal digits

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

google console error `OR-IEH-01`

It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.

Here’s how you can find the details of your transaction:

  1. Sign in to your Google Payments account at https://payments.google.com.

  2. On the left menu, select the “Subscriptions and services” page.

  3. On the “Other purchase activity” card, click View purchases.

  4. Click the “Google Play” registration transaction to see your payment method.

  5. You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.

To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).

How to check if there exists a process with a given pid in Python?

In Windows, you can do it in this way:

import ctypes
PROCESS_QUERY_INFROMATION = 0x1000
def checkPid(pid):
    processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid)
    if processHandle == 0:
        return False
    else:
        ctypes.windll.kernel32.CloseHandle(processHandle)
    return True

First of all, in this code you try to get a handle for process with pid given. If the handle is valid, then close the handle for process and return True; otherwise, you return False. Documentation for OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx

auto create database in Entity Framework Core

If you have created the migrations, you could execute them in the Startup.cs as follows.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
      }
      
      ...

This will create the database and the tables using your added migrations.

If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
      }
      
      ...

Instead.

If you need to delete your database prior to making sure it's created, call:

            context.Database.EnsureDeleted();

Just before you call EnsureCreated()

Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity

How do I add a foreign key to an existing SQLite table?

You can't.

Although the SQL-92 syntax to add a foreign key to your table would be as follows:

ALTER TABLE child ADD CONSTRAINT fk_child_parent
                  FOREIGN KEY (parent_id) 
                  REFERENCES parent(id);

SQLite doesn't support the ADD CONSTRAINT variant of the ALTER TABLE command (sqlite.org: SQL Features That SQLite Does Not Implement).

Therefore, the only way to add a foreign key in sqlite 3.6.1 is during CREATE TABLE as follows:

CREATE TABLE child ( 
    id           INTEGER PRIMARY KEY, 
    parent_id    INTEGER, 
    description  TEXT,
    FOREIGN KEY (parent_id) REFERENCES parent(id)
);

Unfortunately you will have to save the existing data to a temporary table, drop the old table, create the new table with the FK constraint, then copy the data back in from the temporary table. (sqlite.org - FAQ: Q11)

Command to collapse all sections of code?

If you want to collapse/expand an area within a class/method (instead of collapsing the entire class/method), you may create custom regions as follow:

 #region AnyNameforCollapsableRegion

 //Code to collapse

 #endregion 

Reference

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You need to add extra nginx directive (for ngx_http_proxy_module) in nginx.conf, e.g.:

proxy_read_timeout 300;

Basically the nginx proxy_read_timeout directive changes the proxy timeout, the FcgidIOTimeout is for scripts that are quiet too long, and FcgidBusyTimeout is for scripts that take too long to execute.

Also if you're using FastCGI application, increase these options as well:

FcgidBusyTimeout 300
FcgidIOTimeout 250

Then reload nginx and PHP5-FPM.

Plesk

In Plesk, you can add it in Web Server Settings under Additional nginx directives.

For FastCGI check in Web Server Settings under Additional directives for HTTP.

See: How to fix FastCGI timeout issues in Plesk?

Casting a number to a string in TypeScript

window.location.hash is a string, so do this:

var page_number: number = 3;
window.location.hash = String(page_number); 

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

How can I get session id in php and show it?

Before getting a session id you need to start a session and that is done by using: session_start() function.

Now that you have started a session you can get a session id by using: session_id().

/* A small piece of code for setting, displaying and destroying session in PHP */

<?php
session_start();
$r=session_id();

/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */

/* now registering a session for an authenticated user */
$_SESSION['username']=$username;

/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];


/* now destroying the session id */

if(isset($_SESSION['username']))
{
    $_SESSION=array();
    unset($_SESSION);
    session_destroy();
    echo "session destroyed...";
}
?>

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

HTTPS setup in Amazon EC2

An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.

What is the difference between Swing and AWT?

AWT 1 . AWT occupies more memory space 2 . AWT is platform dependent 3 . AWT require javax.awt package

swings 1 . Swing occupies less memory space 2 . Swing component is platform independent 3 . Swing requires javax.swing package

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If it helps anyone, I just appended the contents of the below output file to the existing org.apache.catalina.startup.TldConfig.jarsToSkip= entry.

Note that /var/log/tomcat7/catalina.out is the location of your tomcat log.

egrep "No TLD files were found in \[file:[^\]+\]" /var/log/tomcat7/catalina.out -o | egrep "[^]/]+.jar" -o | sort | uniq | sed -e 's/.jar/.jar,\\/g' > skips.txt

Hope that helps.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

I couldn't properly follow the other answers, here's more of a dummies guide...

You can do this either way round to go trunk -> branch or branch -> trunk. I always first do trunk -> branch fix any conflicts there and then merge branch -> trunk.

Merge trunk into a branch / tag

  1. Checkout the branch / tag
  2. Right-click on the root of the branch | Tortoise SVN | Merge ...
  3. Merge Type: Merge a range of revisions | Click 'Next' enter image description here
  4. Merge revision range: Select the URL of the trunk directory that you copied to the branch / tag. Enter the revisions to merge or leave the field empty to merge all revisions | click 'Next' enter image description here
  5. Merge options: I just left these as default | click 'Merge' enter image description here
  6. This will merge the revisions into the checked out branch / tag
  7. Then commit the merged changes to the branch / tag

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

Single vs Double quotes (' vs ")

I know LOTS of people wouldn't agree, but this is what I do and I really enjoy such a coding style: I actually don't use any quote in HTML unless it is absolutely necessary.

Example:

<form method=post action=#>
<fieldset>
<legend>Register here: </legend>
  <label for=account>Account: </label>
  <input id=account type=text name=account required><br>
  <label for=password>Password: </label>
  <input id=password type=password name=password required><br>
...

Double quotes are used only when there are spaces in the attribute values or whatever:

<form class="val1 val2 val3" method=post action=#>
  ...
</form>

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

PHP preg_replace special characters

If you by writing "non letters and numbers" exclude more than [A-Za-z0-9] (ie. considering letters like åäö to be letters to) and want to be able to accurately handle UTF-8 strings \p{L} and \p{N} will be of aid.

  1. \p{N} will match any "Number"
  2. \p{L} will match any "Letter Character", which includes
    • Lower case letter
    • Modifier letter
    • Other letter
    • Title case letter
    • Upper case letter

Documentation PHP: Unicode Character Properties


$data = "Thäre!wouldn't%bé#äny";

$new_data = str_replace  ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);

var_dump (
  $new_data
);

output

string(23) "Thäre_wouldnt_bé_äny"

How can I use onItemSelected in Android?

I think this will benefit you Try this I'm using to change the language in my application

String[] districts;
Spinner sp;

......

 sp = (Spinner) findViewById(R.id.sp);
         districts = getResources().getStringArray(R.array.lang_array);
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,districts);
         sp.setAdapter(adapter);
         sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
              @Override
             public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
                  // TODO Auto-generated method stub
                  int index = arg0.getSelectedItemPosition();
                  Toast.makeText(getBaseContext(), "You select "+districts[index]+" id "+position, Toast.LENGTH_LONG).show();
                  switch(position){
                      case 0:
                          setLocal("fr");
                          //recreate();
                          break;
                      case 1:
                          setLocal("ar");
                          //recreate();
                          break;
                      case 2:
                          setLocal("en");
                          //recreate();
                          break;
                      default: //For all other cases, do this
                          setLocal("en");
                          //recreate();
                          break;
                  }
              }
             @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                   // TODO Auto-generated method stub
                         }
        });

and this is my String Array

<string-array name="lang_array">
    <item>french</item>
    <item>arabic</item>
    <item>english</item>
</string-array>

Compare two objects with .equals() and == operator

If you dont need to customize the default toString() function, another way is to override toString() method, which returns all attributes to be compared. then compare toString() output of two objects. I generated toString() method using IntelliJ IDEA IDE, which includes class name in the string.

public class Greeting {
private String greeting;

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    return this.toString().equals(obj.toString());
}

@Override
public String toString() {
    return "Greeting{" +
            "greeting='" + greeting + '\'' +
            '}';
}
}

Get top 1 row of each group

If you're worried about performance, you can also do this with MAX():

SELECT *
FROM DocumentStatusLogs D
WHERE DateCreated = (SELECT MAX(DateCreated) FROM DocumentStatusLogs WHERE ID = D.ID)

ROW_NUMBER() requires a sort of all the rows in your SELECT statement, whereas MAX does not. Should drastically speed up your query.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Consideration must also be given to your individual FPM pools, if any.

I couldn't figure out why none of these answers was working for me today. This had been a set-and-forget scenario for me, where I had forgotten that listen.user and listen.group were duplicated on a per-pool basis.

If you used pools for different user accounts like I did, where each user account owns their FPM processes and sockets, setting only the default listen.owner and listen.group configuration options to 'nginx' will simply not work. And obviously, letting 'nginx' own them all is not acceptable either.

For each pool, make sure that

listen.group = nginx

Otherwise, you can leave the pool's ownership and such alone.

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

How to directly initialize a HashMap (in a literal way)?

Based on @johnny-willer's answer, you cannot get a map with null values on Java 8 because of Collectors.toMap relies on Map.merge. This method does not expect null values, so it throws a NullPointerException as it was described in this bug report: https://bugs.openjdk.java.net/browse/JDK-8148463

An alternative way to get a map with null values using a builder syntax on Java 8 is writing an inline collector:

Map<String, String> myMap = Stream.of(
         new SimpleEntry<>("key1", "value1"),
         new SimpleEntry<>("key2", (String) null),
         new SimpleEntry<>("key3", "value3"))
        .collect(HashMap::new,
                (map, entry) -> map.put(entry.getKey(),
                                        entry.getValue()),
                HashMap::putAll);

Also, this implementation will replace a value if the key appears multiple times. The default Collectors.toMap, without a custom merge function like (prev, next) -> next, will throw an IllegalStatException instead.

keypress, ctrl+c (or some combo like that)

As of 2019, this works (in Chrome at least)

$(document).keypress(function(e) {
    var key = (event.which || event.keyCode) ;
  if(e.ctrlKey) {
        if (key == 26) { console.log('Ctrl+Z was pressed') ; }
        else if (key == 25) { console.log('Ctrl+Y was pressed') ; }
        else if (key == 19) { console.log('Ctrl+S was pressed') ; }
    else { console.log('Ctrl', key, 'was pressed') ; }
    }
});

pandas DataFrame: replace nan values with average of columns

If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.

sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))

Call web service in excel

In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.

Sub Demo()
    Dim XDoc As MSXML2.DOMDocument
    Dim xEmpDetails As MSXML2.IXMLDOMNode
    Dim xParent As MSXML2.IXMLDOMNode
    Dim xChild As MSXML2.IXMLDOMNode
    Dim query As String
    Dim Col, Row As Integer
    Dim objWS As New clsws_GlobalWeather

    Set XDoc = New MSXML2.DOMDocument
    XDoc.async = False
    XDoc.validateOnParse = False
    query = objWS.wsm_GetCitiesByCountry("india")

    If Not XDoc.LoadXML(query) Then  'strXML is the string with XML'
        Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
    End If
    XDoc.LoadXML (query)

    Set xEmpDetails = XDoc.DocumentElement
    Set xParent = xEmpDetails.FirstChild
    Worksheets("Sheet3").Cells(1, 1).Value = "Country"
    Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
    Worksheets("Sheet3").Cells(1, 2).Value = "City"
    Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
    Row = 2
    Col = 1
    For Each xParent In xEmpDetails.ChildNodes
        For Each xChild In xParent.ChildNodes
            Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
            Col = Col + 1
        Next xChild
        Row = Row + 1
        Col = 1
    Next xParent
End Sub

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

Immutable array in Java

Well.. arrays are useful to pass as constants (if they were) as variants parameters.

Bind class toggle to window scroll event

What about performance?

  1. Always debounce events to reduce calculations
  2. Use scope.applyAsync to reduce overall digest cycles count
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            func.apply(context, args);
        };

        if (!timeout) func.apply(context, args);
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

angular.module('app.layout')
  .directive('classScroll', function ($window) {    
    return {
        restrict: 'A',
        link: function (scope, element) {    
            function toggle() {
                angular.element(element)
                  .toggleClass('class-scroll--scrolled', 
                    window.pageYOffset > 0);
                scope.$applyAsync();
            }    
            angular.element($window)
              .on('scroll', debounce(toggle, 50));

            toggle();
        }
    };
});

3. If you don't need to trigger watchers/digests at all then use compile

.directive('classScroll', function ($window, utils) {
    return {
        restrict: 'A',
        compile: function (element, attributes) {
            function toggle() {
                angular.element(element)
                  .toggleClass(attributes.classScroll,
                    window.pageYOffset > 0);
            }

            angular.element($window)
              .on('scroll', utils.debounce(toggle, 50));
            toggle();
        }
    };
  });

And you can use it like <header class-scroll="header--scrolled">

sqlplus how to find details of the currently connected database session

Try:

select * from v$session where sid = SYS_CONTEXT('USERENV','SID');

You might also be interested in this AskTom post

After seing your comment, you can do:

SELECT * FROM global_name;

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

On Android Studio

Open the AVD Manager.

enter image description here

Click Edit Icon to edit the AVD.

enter image description here

Click Show Advanced settings.

enter image description here

Change the Internal Storage, Ram, SD Card size as necessary. Click Finish.

enter image description here

Confirm the popup by clicking yes.

enter image description here

Wipe Data on the AVD and confirm the popup by clicking yes.

enter image description here

Important: After increasing the size, if it doesn't automatically ask you to wipe data, you have to do it manually by opening the AVD's pull-down menu and choosing Wipe Data.

enter image description here

Now start and use your Emulator with increased storage.

Find text string using jQuery?

Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });

Android OnClickListener - identify a button

Button mybutton = new Button(ViewPagerSample.this);
mybutton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

Common xlabel/ylabel for matplotlib subplots

It will look better if you reserve space for the common labels by making invisible labels for the subplot in the bottom left corner. It is also good to pass in the fontsize from rcParams. This way, the common labels will change size with your rc setup, and the axes will also be adjusted to leave space for the common labels.

fig_size = [8, 6]
fig, ax = plt.subplots(5, 2, sharex=True, sharey=True, figsize=fig_size)
# Reserve space for axis labels
ax[-1, 0].set_xlabel('.', color=(0, 0, 0, 0))
ax[-1, 0].set_ylabel('.', color=(0, 0, 0, 0))
# Make common axis labels
fig.text(0.5, 0.04, 'common X', va='center', ha='center', fontsize=rcParams['axes.labelsize'])
fig.text(0.04, 0.5, 'common Y', va='center', ha='center', rotation='vertical', fontsize=rcParams['axes.labelsize'])

enter image description here enter image description here