Programs & Examples On #Menuitem

A menu item is a child element of a menu that provides the user a means to view and execute a specific application operation.

How to add "active" class to wp_nav_menu() current menu item (simple way)

In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

android: changing option menu items programmatically

For anyone needs to change the options of the menu dynamically:

private Menu menu;

// ...

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    this.menu = menu;
    getMenuInflater().inflate(R.menu.options, menu);
    return true;
}

// ...

private void hideOption(int id)
{
    MenuItem item = menu.findItem(id);
    item.setVisible(false);
}

private void showOption(int id)
{
    MenuItem item = menu.findItem(id);
    item.setVisible(true);
}

private void setOptionTitle(int id, String title)
{
    MenuItem item = menu.findItem(id);
    item.setTitle(title);
}

private void setOptionIcon(int id, int iconRes)
{
    MenuItem item = menu.findItem(id);
    item.setIcon(iconRes);
}

How to change menu item text dynamically in Android

As JxDarkAngel suggested, calling this from anywhere in your Activity,

invalidateOptionsMenu();

and then overriding:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  MenuItem item = menu.findItem(R.id.bedSwitch);
    if (item.getTitle().equals("Set to 'In bed'")) {
        item.setTitle("Set to 'Out of bed'");
        inBed = false;
    } else {
        item.setTitle("Set to 'In bed'");
        inBed = true;
    }
  return super.onPrepareOptionsMenu(menu);
}

is a much better choice. I used the answer from https://stackoverflow.com/a/17496503/568197

Android: How to enable/disable option menu item on button click?

Anyway, the documentation covers all the things.

Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

E.g.

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    if (isFinalized) {
        menu.getItem(1).setEnabled(false);
        // You can also use something like:
        // menu.findItem(R.id.example_foobar).setEnabled(false);
    }
    return true;
}

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Copied from this link " ... Important We strongly recommend that you do not work around this problem by turning off the Prevent saving changes that require table re-creation option. For more information about the risks of turning off this option, see the "More information" section. ''

" ...To work around this problem, use Transact-SQL statements to make the changes to the metadata structure of a table. For additional information refer to the following topic in SQL Server Books Online

For example, to change MyDate column of type datetime in at table called MyTable to accept NULL values you can use:

alter table MyTable alter column MyDate7 datetime NULL "

How do I hide a menu item in the actionbar?

I think a better approach would be to use a member variable for the menu, initialize it in onCreateOptionsMenu() and just use setVisible() afterwards, without invalidating the options menu.

How do I center align horizontal <UL> menu?

Try this:

div.topmenu-design ul
{
  display:block;
  width:600px; /* or whatever width value */
  margin:0px auto;
}

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

How to change the Text color of Menu item in Android?

I was using Material design and when the toolbar was on a small screen clicking the more options would show a blank white drop down box. To fix this I think added this to the main AppTheme:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:itemTextAppearance">@style/menuItem</item>
</style>

And then created a style where you set the textColor for the menu items to your desired colour.

<style name="menuItem" parent="Widget.AppCompat.TextView.SpinnerItem">
    <item name="android:textColor">@color/black</item>
</style>

The parent name Widget.AppCompat.TextView.SpinnerItem I don't think that matters too much, it should still work.

How to clear react-native cache?

Currently, it is built using npx, so it needs to be updated.

Terminal : npx react-native start --reset-cache

IOS : Xcode -> Product -> Clean Build Folder

Android : Android Studio -> Build -> Clean Project

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

When to use in vs ref vs out

You can use the out contextual keyword in two contexts (each is a link to detailed information), as a parameter modifier or in generic type parameter declarations in interfaces and delegates. This topic discusses the parameter modifier, but you can see this other topic for information on the generic type parameter declarations.

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example: C#

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile: C#

class CS0663_Example
{
    // Compiler error CS0663: "Cannot define overloaded 
    // methods that differ only on ref and out".
    public void SampleMethod(out int i) { }
    public void SampleMethod(ref int i) { }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this: C#

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

Properties are not variables and therefore cannot be passed as out parameters.

For information about passing arrays, see Passing Arrays Using ref and out (C# Programming Guide).

You can't use the ref and out keywords for the following kinds of methods:

Async methods, which you define by using the async modifier.

Iterator methods, which include a yield return or yield break statement.

Example

Declaring an out method is useful when you want a method to return multiple values. The following example uses out to return three variables with a single method call. Note that the third argument is assigned to null. This enables methods to return values optionally. C#

class OutReturnExample
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1, str2;
        Method(out value, out str1, out str2);
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }
}

Remove large .pack file created by git

Scenario A: If your large files were only added to a branch, you don't need to run git filter-branch. You just need to delete the branch and run garbage collection:

git branch -D mybranch
git reflog expire --expire-unreachable=all --all
git gc --prune=all

Scenario B: However, it looks like based on your bash history, that you did merge the changes into master. If you haven't shared the changes with anyone (no git push yet). The easiest thing would be to reset master back to before the merge with the branch that had the big files. This will eliminate all commits from your branch and all commits made to master after the merge. So you might lose changes -- in addition to the big files -- that you may have actually wanted:

git checkout master
git log # Find the commit hash just before the merge
git reset --hard <commit hash>

Then run the steps from the scenario A.

Scenario C: If there were other changes from the branch or changes on master after the merge that you want to keep, it would be best to rebase master and selectively include commits that you want:

git checkout master
git log # Find the commit hash just before the merge
git rebase -i <commit hash>

In your editor, remove lines that correspond to the commits that added the large files, but leave everything else as is. Save and quit. Your master branch should only contain what you want, and no large files. Note that git rebase without -p will eliminate merge commits, so you'll be left with a linear history for master after <commit hash>. This is probably okay for you, but if not, you could try with -p, but git help rebase says combining -p with the -i option explicitly is generally not a good idea unless you know what you are doing.

Then run the commands from scenario A.

How to use MySQL dump from a remote machine

This is how you would restore a backup after you successfully backup your .sql file

mysql -u [username] [databasename]

And choose your sql file with this command:

source MY-BACKED-UP-DATABASE-FILE.sql

Jenkins: Can comments be added to a Jenkinsfile?

Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc to process your Jenkinsfile (s).

First, groovydoc chokes on files without extensions with the wonderful error

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
    at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
    at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
    ... 6 more

... and second, as far as I can tell Javadoc-style commments at the start of a groovy script are ignored. So even if you copy/rename your Jenkinsfile to Jenkinsfile.groovy, you won't get much useful output.

I want to be able to use a

/**
 * Document my Jenkinsfile's overall purpose here
 */

comment at the start of my Jenkinsfile. No such luck (yet).

groovydoc will process classes and methods defined in your Jenkinsfile if you pass -private to the command, though.

What is the difference between single-quoted and double-quoted strings in PHP?

The difference between using single quotes and double quotes in php is that if we use single quotes in echo statement then it is treated as a string. ... but if we enter variable name within double quotes then it will output the value of that variable along with the string.

jQuery-- Populate select from json

I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.

var temp= ['one', 'two', 'three']; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

Output:

<option value="0">one</option><option value="1">two</option><option value="2">three</option>

However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.

var temp= "['one', 'two', 'three']"; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

How do I revert back to an OpenWrt router configuration?

You can run this command for making a factory reset:

killall dropbear uhttpd; sleep 1; mtd -r erase rootfs_data

GitHub: How to make a fork of public repository private?

Just go to https://github.com/new/import .

GitHub Import

In the section "Your old repository's clone URL" paste the repo URL you want and in "Privacy" select Private.

Trying to load local JSON file to show data in a html page using JQuery

I would try to save my object as .txt file and then fetch it like this:

 $.get('yourJsonFileAsString.txt', function(data) {
   console.log( $.parseJSON( data ) );
 }); 

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

How to easily import multiple sql files into a MySQL database?

  1. Goto cmd

  2. Type in command prompt C:\users\Usersname>cd [.sql tables folder path ]
    Press Enter
    Ex: C:\users\Usersname>cd E:\project\database

  3. Type command prompt
    C:\users\Usersname>[.sql folder's drive (directory)name]
    Press Enter
    Ex: C:\users\Usersname>E:

  4. Type command prompt for marge all .sql file(table) in a single file
    copy /b *.sql newdatabase.sql
    Press Enter
    EX: E:\project\database>copy /b *.sql newdatabase.sql

  5. You can see Merge Multiple .sql(file) tables Files Into A Single File in your directory folder
    Ex: E:\project\database

Get current URL/URI without some of $_GET variables

Most of the answers are wrong.

The Question is to get url without some query param .

Here is the function that works. It does more things actually. You can remove the param that you don't want and you can add or modify an existing one.

/**
 * Function merges the query string values with the given array and returns the new URL
 * @param string $route
 * @param array $mergeQueryVars
 * @param array $removeQueryVars
 * @return string
 */
public static function getUpdatedUrl($route = '', $mergeQueryVars = [], $removeQueryVars = [])
{
    $currentParams = $request = Yii::$app->request->getQueryParams();

    foreach($mergeQueryVars as $key=> $value)
    {
        $currentParams[$key] = $value;
    }

    foreach($removeQueryVars as $queryVar)
    {
        unset($currentParams[$queryVar]);
    }

    $currentParams[0] = $route == '' ? Yii::$app->controller->getRoute() : $route;

    return Yii::$app->urlManager->createUrl($currentParams);

}

usage:

ClassName:: getUpdatedUrl('',[],['remove_this1','remove_this2'])

This will remove query params 'remove_this1' and 'remove_this2' from URL and return you the new URL

How do you see recent SVN log entries?

Besides what Bert F said, many commands, including log has the -r (or --revision) option. The following are some practical examples using this option to show ranges of revisions:

To list everything in ascending order:

svn log -r 1:HEAD

To list everything in descending order:

svn log -r HEAD:1

To list everything from the thirteenth to the base of the currently checked-out revision in ascending order:

svn log -r 13:BASE

To get everything between the given dates:

svn log -r {2011-02-02}:{2011-02-03}

You can combine all the above expressions with the --limit option, so that can you have a quite granular control over what is printed. For more info about these -r expressions refer to svn help log or the relevant chapter in the book Version Control with Subversion

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

How to export all data from table to an insertable sql format?

I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).

If you dont have identity column in table B_table:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.

In case if you dont have existing B_table in B_db

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

will create table B_table in database B_db with all existing values

Javascript Thousand Separator / string format

Updated using look-behind support in line with ECMAScript2018 changes.
For backwards compatibility, scroll further down to see the original solution.

A regular expression may be used - notably useful in dealing with big numbers stored as strings.

_x000D_
_x000D_
const format = num => _x000D_
    String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')_x000D_
_x000D_
;[_x000D_
    format(100),                           // "100"_x000D_
    format(1000),                          // "1,000"_x000D_
    format(1e10),                          // "10,000,000,000"  _x000D_
    format(1000.001001),                   // "1,000.001001"_x000D_
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
    .forEach(n => console.log(n))
_x000D_
_x000D_
_x000D_

» Verbose regex explanation (regex101.com) flow diagram


This original answer may not be required but can be used for backwards compatibility.

Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.

_x000D_
_x000D_
const format = num => {_x000D_
    const n = String(num),_x000D_
          p = n.indexOf('.')_x000D_
    return n.replace(_x000D_
        /\d(?=(?:\d{3})+(?:\.|$))/g,_x000D_
        (m, i) => p < 0 || i < p ? `${m},` : m_x000D_
    )_x000D_
}_x000D_
_x000D_
;[_x000D_
    format(100),                           // "100"_x000D_
    format(1000),                          // "1,000"_x000D_
    format(1e10),                          // "10,000,000,000"  _x000D_
    format(1000.001001),                   // "1,000.001001"_x000D_
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
    .forEach(n => console.log(n))
_x000D_
_x000D_
_x000D_

» Verbose regex explanation (regex101.com)

flow diagram

jQuery: enabling/disabling datepicker

$('#ElementID').unbind('focus');

did the trick for me !!

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.

So, yes, the launch screens need to be that size.

The maths:

The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.

The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.

In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.

compareTo with primitives -> Integer / int

They're already ints. Why not just use subtraction?

compare = a - b;

Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.

Ant: How to execute a command for each file in directory?

Short Answer

Use <foreach> with a nested <FileSet>

Foreach requires ant-contrib.

Updated Example for recent ant-contrib:

<target name="foo">
  <foreach target="bar" param="theFile">
    <fileset dir="${server.src}" casesensitive="yes">
      <include name="**/*.java"/>
      <exclude name="**/*Test*"/>
    </fileset>
  </foreach>
</target>

<target name="bar">
  <echo message="${theFile}"/>
</target>

This will antcall the target "bar" with the ${theFile} resulting in the current file.

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

What does auto do in margin:0 auto?

auto: The browser sets the margin. The result of this is dependant of the browser

margin:0 auto specifies

* top and bottom margins are 0
* right and left margins are auto

jQuery.animate() with css class only, without explicit styles

In many cases you're better off using CSS transitions for this, and in old browsers the easing will simply be instant. Most animations (like fade in/out) are very trivial to implement and the browser does all the legwork for you. https://developer.mozilla.org/en/docs/Web/CSS/transition

How to execute Python scripts in Windows?

I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux). My package contains a number of scripts with command line options.

I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line. As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.

I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.

For a Python script test, create two files: a test.bat and a test-script.py.

test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):

@echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*

test-script.py is your actual Python script:

import sys
print sys.argv

If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing

test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']

If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix

test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']

Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.

How to consume REST in Java

If you also need to convert that xml string that comes as a response to the service call, an x object you need can do it as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
SAXException {

try {

URL url = new URL(
    "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
    + conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
    (conn.getInputStream())));

String output;

Ciudades ciudades = new Ciudades();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println("12132312");
System.err.println(output);

DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);

    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);

    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

conn.disconnect();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

Note that the xml structure that I expected in the example was as follows:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

Bootstrap-select - how to fire event on change

Easiest implementation.

<script>
    $( ".selectpicker" ).change(function() {
        alert( "Handler for .change() called." );
    });
</script>

How to handle change of checkbox using jQuery?

Hope, this would be of some help.

$('input[type=checkbox]').change(function () {
    if ($(this).prop("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

How to name variables on the fly?

It seems to me that you might be better off with a list rather than using orca1, orca2, etc, ... then it would be orca[1], orca[2], ...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list()
orca[1] <- "Hi"
orca[2] <- 59

Otherwise, assign is just what you want.

Windows equivalent of the 'tail' command

There's a free head utility on this page that you can use. I haven't tried it yet.

Android: How do I get string from resources using its name?

Not from activities only:

    public static String getStringByIdName(Context context, String idName) {
        Resources res = context.getResources();
        return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
    }

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

Switch in Laravel 5 - Blade

Updated 2020 Answer

Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.

@switch($login_error)
    @case(1)
        <span> `E-mail` input is empty!</span>
        @break

    @case(2)
        <span>`Password` input is empty!</span>
        @break

    @default
        <span>Something went wrong, please try again</span>
@endswitch

Older Answer

Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.

Option 1:

@if ($login_error == 1)
    `E-mail` input is empty!
@elseif ($login_error == 2)
    `Password` input is empty!
@endif

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

Interop type cannot be embedded

In most cases, this error is the result of code which tries to instantiate a COM object. For example, here is a piece of code starting up Excel:

Excel.ApplicationClass xlapp = new Excel.ApplicationClass();

Typically, in .NET 4 you just need to remove the 'Class' suffix and compile the code:

Excel.Application xlapp = new Excel.Application();

An MSDN explanation is here.

How to remove button shadow (android)

Using this as the background for your button might help, change the color to your needs

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_light" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_dark" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
</selector>

How to load a UIView using a nib file created with Interface Builder

I ended up adding a category to UIView for this:

 #import "UIViewNibLoading.h"

 @implementation UIView (UIViewNibLoading)

 + (id) loadNibNamed:(NSString *) nibName {
    return [UIView loadNibNamed:nibName fromBundle:[NSBundle mainBundle] retainingObjectWithTag:1];
 }

 + (id) loadNibNamed:(NSString *) nibName fromBundle:(NSBundle *) bundle retainingObjectWithTag:(NSUInteger) tag {
    NSArray * nib = [bundle loadNibNamed:nibName owner:nil options:nil];
    if(!nib) return nil;
    UIView * target = nil;
    for(UIView * view in nib) {
        if(view.tag == tag) {
            target = [view retain];
            break;
        }
    }
    if(target && [target respondsToSelector:@selector(viewDidLoad)]) {
        [target performSelector:@selector(viewDidLoad)];
    }
    return [target autorelease];
 }

 @end

explanation here: viewcontroller is less view loading in ios&mac

Foreach loop, determine which is the last iteration of the loop

Just store the previous value and work with it inside the loop. Then at the end the 'previous' value will be the last item, letting you handle it differently. No counting or special libraries required.

bool empty = true;
Item previousItem;

foreach (Item result in Model.Results)
{
    if (!empty)
    {
        // We know this isn't the last item because it came from the previous iteration
        handleRegularItem(previousItem);
    }

    previousItem = result;
    empty = false;
}

if (!empty)
{
    // We know this is the last item because the loop is finished
    handleLastItem(previousItem);
}

Enabling error display in PHP via htaccess only

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess. This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

Selecting a Linux I/O Scheduler

As documented in /usr/src/linux/Documentation/block/switching-sched.txt, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.

# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq

Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:

  • noop is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
  • deadline is a lightweight scheduler which tries to put a hard limit on latency
  • cfq tries to maintain system-wide fairness of I/O bandwidth

The default was anticipatory for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory has a long history of being tunable for best performance on these workloads, and deadline very quickly passes all requests through to the underlying device.

How to bind 'touchstart' and 'click' events but not respond to both?

It may be effective to assign to the events 'touchstart mousedown' or 'touchend mouseup' to avoid undesired side-effects of using click.

How to add bootstrap to an angular-cli project

I guess the above methods have changed after the release, check this link out

https://github.com/valor-software/ng2-bootstrap/blob/development/docs/getting-started/ng-cli.md

initiate project

npm i -g angular-cli
ng new my-app
cd my-app
ng serve
npm install --save @ng-bootstrap/ng-bootstrap

install ng-bootstrap and bootstrap

npm install ng2-bootstrap bootstrap --save

open src/app/app.module.ts and add

import { AlertModule } from 'ng2-bootstrap/ng2-bootstrap';
...

@NgModule({
   ...
   imports: [AlertModule, ... ],
    ... 
})

open angular-cli.json and insert a new entry into the styles array

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ],

open src/app/app.component.html and test all works by adding

<alert type="success">hello</alert>

PHP Multiple Checkbox Array

You need to use the square brackets notation to have values sent as an array:

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>

Please note though, that only the values of only checked checkboxes will be sent.

Python loop counter in a for loop

You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

How do you transfer or export SQL Server 2005 data to Excel

you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel.

Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.

How to display Toast in Android?

This worked for me:

Toast.makeText(getBaseContext(), "your text here" , Toast.LENGTH_SHORT ).show();

How to test the type of a thrown exception in Jest

In case you are working with Promises:

await expect(Promise.reject(new HttpException('Error message', 402)))
  .rejects.toThrowError(HttpException);

Laravel Migration table already exists, but I want to add new not the older

You need to run

php artisan migrate:rollback

if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your user table when you ran a previous rollback did not drop the table.

EDIT:

The reason this happens is that you ran a rollback previously and it had some error in the code or did not drop the table. This still however messes up the laravel migration table and as far as it's concerned you now have no record of pushing the user table up. The user table does already exist however and this error is throw.

Adding content to a linear layout dynamically?

In your onCreate(), write the following

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1, view2 and view3 are your TextViews. They're easily created programmatically.

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

Eclipse/Java code completion not working

Check that you did not filter out many options inside the Window > Preferences > Java > Appearance > Type Filters

Items in this list will not be appear in quick fix, be autocompleted, or appear in other various places like the Open Type dialog.

How do I remove blue "selected" outline on buttons?

You can remove this by adding !important to your outline.

button{
 outline: none !important;
}

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Random date in C#

This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.

Func<DateTime> RandomDayFunc()
{
    DateTime start = new DateTime(1995, 1, 1); 
    Random gen = new Random(); 
    int range = ((TimeSpan)(DateTime.Today - start)).Days; 
    return () => start.AddDays(gen.Next(range));
}

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think that more accurate is this syntax:

SELECT CONVERT(CHAR(10), GETDATE(), 103)

I add SELECT and GETDATE() for instant testing purposes :)

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

Multiple actions were found that match the request in Web Api

Make sure you do NOT decorate your Controller methods for the default GET|PUT|POST|DELETE actions with [HttpPost/Put/Get/Delete] attribute. I had added this attibute to my vanilla Post controller action and it caused a 404.

Hope this helps someone as it can be very frustrating and bring progress to a halt.

How do I get indices of N maximum values in a NumPy array?

bottleneck has a partial sort function, if the expense of sorting the entire array just to get the N largest values is too great.

I know nothing about this module; I just googled numpy partial sort.

Determine distance from the top of a div to top of window with javascript

You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

The distance variable now holds the distance from the top of the #my-element element and the top-fold.

Here is a demo: http://jsfiddle.net/Rxs2m/

Note that negative values mean that the element is above the top-fold.

Angularjs ng-model doesn't work inside ng-if

Yes, ng-hide (or ng-show) directive won't create child scope.

Here is my practice:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>

<script>
    function main($scope) {
        $scope.testa = false;
        $scope.testb = false;
        $scope.testc = false;
        $scope.testd = false;
    }
</script>

<div ng-app >
    <div ng-controller="main">

        Test A: {{testa}}<br />
        Test B: {{testb}}<br />
        Test C: {{testc}}<br />
        Test D: {{testd}}<br />

        <div>
            testa (without ng-if): <input type="checkbox" ng-model="testa" />
        </div>
        <div ng-if="!testa">
            testb (with ng-if): <input type="checkbox" ng-model="$parent.testb" />
        </div>
        <div ng-show="!testa">
            testc (with ng-show): <input type="checkbox" ng-model="testc" />
        </div>
        <div ng-hide="testa">
            testd (with ng-hide): <input type="checkbox" ng-model="testd" />
        </div>

    </div>
</div>

http://jsfiddle.net/bn64Lrzu/

JavaScript - Get Portion of URL Path

In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse

const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');

According to the documentation, it extracts the following parts:

The returned url instance contains the following properties:

protocol: The protocol scheme of the URL (e.g. http:). slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//). auth: Authentication information portion (e.g. username:password). username: Username of basic authentication. password: Password of basic authentication. host: Host name with port number. hostname: Host name without port number. port: Optional port number. pathname: URL path. query: Parsed object containing query string, unless parsing is set to false. hash: The "fragment" portion of the URL including the pound-sign (#). href: The full URL. origin: The origin of the URL.

How to prevent Screen Capture in Android

I saw all of the answers which are appropriate only for a single activity but there is my solution which will block screenshot for all of the activities without adding any code to the activity. First of all make an Custom Application class and add a registerActivityLifecycleCallbacks.Then register it in your manifest.

MyApplicationContext.class

public class MyApplicationContext extends Application {
    private  Context context;
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        setupActivityListener();
    }

    private void setupActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);            }
            @Override
            public void onActivityStarted(Activity activity) {
            }
            @Override
            public void onActivityResumed(Activity activity) {

            }
            @Override
            public void onActivityPaused(Activity activity) {

            }
            @Override
            public void onActivityStopped(Activity activity) {
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }



}

Manifest

 <application
        android:name=".MyApplicationContext"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Update ViewPager dynamically?

I have lived same problem and I have searched too much times. Any answer given in stackoverflow or via google was not solution for my problem. My problem was easy. I have a list, I show this list with viewpager. When I add a new element to head of the list and I refresh the viewpager nothings changed. My final solution was very easy anybody can use. When a new element added to list and want to refresh the list. Firstly set viewpager adapter to null then recreate the adapter and set i to it to viewpager.

myVPager.setAdapter(null);
myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),newList);
myVPager.setAdapter(myFragmentAdapter);

Be sure your adapter must extend FragmentStatePagerAdapter

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

How do I get the time of day in javascript/Node.js?

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var day  = date.getDate();
day = (hour > 12 ? "" : "") + day - 1;
day = (day < 10 ? "0" : "") + day;
x = ":"
console.log( month + x + day + x + year )

It will display the date in the month, day, then the year

HTML Agility pack - parsing tables

In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:

    List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
                                       from row in table?.SelectNodes(HtmlBody.TR)
                                       let rows = row.SelectSingleNode(HtmlBody.TR)
                                       where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
                                       select new TableRow
                                       {
                                           Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
                                           Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
                                       }  

TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:

_x000D_
_x000D_
<tr>_x000D_
    <td width="28%">&nbsp;</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.

Jquery Validate custom error message location

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});

Spring cron expression for every day 1:01:am

Something missing from gipinani's answer

@Scheduled(cron = "0 1 1,13 * * ?", zone = "CST")

This will execute at 1.01 and 13.01. It can be used when you need to run the job without a pattern multiple times a day.

And the zone attribute is very useful, when you do deployments in remote servers. This was introduced with spring 4.

How to remove the bottom border of a box with CSS

Just add in: border-bottom: none;

#index-03 {
    position:absolute;
    border: .1px solid #900;
    border-bottom: none;
    left:0px;
    top:102px;
    width:900px;
    height:27px;
}

Class vs. static method in JavaScript

Javascript has no actual classes rather it uses a system of prototypal inheritance in which objects 'inherit' from other objects via their prototype chain. This is best explained via code itself:

_x000D_
_x000D_
function Foo() {};_x000D_
// creates a new function object_x000D_
_x000D_
Foo.prototype.talk = function () {_x000D_
    console.log('hello~\n');_x000D_
};_x000D_
// put a new function (object) on the prototype (object) of the Foo function object_x000D_
_x000D_
var a = new Foo;_x000D_
// When foo is created using the new keyword it automatically has a reference _x000D_
// to the prototype property of the Foo function_x000D_
_x000D_
// We can show this with the following code_x000D_
console.log(Object.getPrototypeOf(a) === Foo.prototype); _x000D_
_x000D_
a.talk(); // 'hello~\n'_x000D_
// When the talk method is invoked it will first look on the object a for the talk method,_x000D_
// when this is not present it will look on the prototype of a (i.e. Foo.prototype)_x000D_
_x000D_
// When you want to call_x000D_
// Foo.talk();_x000D_
// this will not work because you haven't put the talk() property on the Foo_x000D_
// function object. Rather it is located on the prototype property of Foo._x000D_
_x000D_
// We could make it work like this:_x000D_
Foo.sayhi = function () {_x000D_
    console.log('hello there');_x000D_
};_x000D_
_x000D_
Foo.sayhi();_x000D_
// This works now. However it will not be present on the prototype chain _x000D_
// of objects we create out of Foo
_x000D_
_x000D_
_x000D_

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

How to Execute SQL Script File in Java?

Try this code:

String strProc =
         "DECLARE \n" +
         "   sys_date DATE;"+
         "" +
         "BEGIN\n" +
         "" +
         "   SELECT SYSDATE INTO sys_date FROM dual;\n" +
         "" +
         "END;\n";

try{
    DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver () );
    Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@your_db_IP:1521:your_db_SID","user","password");  
    PreparedStatement psProcToexecute = connection.prepareStatement(strProc);
    psProcToexecute.execute();
}catch (Exception e) {
    System.out.println(e.toString());  
}

Android Studio error: "Environment variable does not point to a valid JVM installation"

The answer to this question can be found here

goto the AndroidStudio installation folder.
goto bin folder and open studio.bat in text editor
add set JAVA_HOME=C:\Program Files\Java2\jdk1.8.0//your java path after the ECHO line.
goto Start -> All Programmes -> Android Studio ->
right click on Android Studio and click on properties.
You will see the Target something like <installation path>android-studio\bin\studio64.exe
change it to <installation path>android-studio\bin\studio.bat

or..... even this might work

Java_Home path set to its parent folder to C:\Program Files\Java\jdk1.8.0_25

DropDownList in MVC 4 with Razor

This can also be done like

@model IEnumerable<ItemList>

_x000D_
_x000D_
<select id="dropdowntipo">_x000D_
    <option value="0">Select Item</option>_x000D_
    _x000D_
    @{_x000D_
      foreach(var item in Model)_x000D_
      {_x000D_
        <option value= "@item.Value">@item.DisplayText</option>_x000D_
      }_x000D_
    }_x000D_
_x000D_
</select>
_x000D_
_x000D_
_x000D_

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

How to tell if a string is not defined in a Bash shell script

Here is what I think is a much clearer way to check if a variable is defined:

var_defined() {
    local var_name=$1
    set | grep "^${var_name}=" 1>/dev/null
    return $?
}

Use it as follows:

if var_defined foo; then
    echo "foo is defined"
else
    echo "foo is not defined"
fi

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

Flash CS4 refuses to let go

Use a grep analog to find the strings oldnamespace and Jenine inside the files in your whole project folder. Then you'd know what step to do next.

How can I transform string to UTF-8 in C#?

 Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(mystring));

How can I find all the subsets of a set, with exactly n elements?

Here is one neat way with easy to understand algorithm.

import copy

nums = [2,3,4,5]
subsets = [[]]

for n in nums:
    prev = copy.deepcopy(subsets)
    [k.append(n) for k in subsets]
    subsets.extend(prev)

print(subsets) 
print(len(subsets))

# [[2, 3, 4, 5], [3, 4, 5], [2, 4, 5], [4, 5], [2, 3, 5], [3, 5], [2, 5], [5], 
# [2, 3, 4], [3, 4], [2, 4], [4], [2, 3], [3], [2], []]

# 16 (2^len(nums))

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);

How to get domain URL and application name?

The following code might be useful for web application using JavaScript.

var newURL = window.location.protocol + "//"  + window.location.host + "" + window.location.pathname;

newURL = newURL.substring(0,newURL.indexOf(""));

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

not:first-child selector

not(:first-child) does not seem to work anymore. At least with the more recent versions of Chrome and Firefox.

Instead, try this:

ul:not(:first-of-type) {}

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

How to call Base Class's __init__ method from the child class?

If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.

How to run .sql file in Oracle SQL developer tool to import database?

You can use Load function

Load TableName fullfilepath; 

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:

OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);

A simpler way to do the same case is:

SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
        newDateFormat.parse(newDateFormat.format(
                new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
                        .parse(rs.getString("originalRevisionDate", "")))));

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.

Given a ComboBox "combobox" on a windows form and a class SomeClass with the string type property Name,

List<SomeClass> list = new List<SomeClass>();

combobox.DisplayMember = "Name";
combobox.DataSource = list;

Which means that combobox.SelectedItem is a SomeClass object from list, and each item in combobox will be displayed using its property Name.

You can read the selected item using

SomeClass someClass = (SomeClass)combobox.SelectedItem;

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

UIImage: Resize, then Crop

The following simple code worked for me.

[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];

Git push rejected "non-fast-forward"

Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.

 git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch

Get Country of IP Address with PHP

Install and use PHP's GeoIP extension if you can. On debian lenny:

sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7

and then try it in PHP:

$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;

returns:

The current user is located in: Cameroon

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How can I import Swift code to Objective-C?

If you have a project created in Swift 4 and then added Objective-C files, do it like this:

@objcMembers
public class MyModel: NSObject {
    var someFlag = false         
    func doSomething() {         
        print("doing something")
    }
}

Reference: https://useyourloaf.com/blog/objc-warnings-upgrading-to-swift-4/

How can I convert a VBScript to an executable (EXE) file?

More info

To find a compiler, you'll have 1 per .net version installed, type in a command prompt.

dir c:\Windows\Microsoft.NET\vbc.exe /a/s

Windows Forms

For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).

Compile line in a command prompt.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"

Text for VBS2EXE.vb

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub

Public Sub New() 

InitializeComponent() 

End Sub

Public Shared Sub Main() 

Dim sc as object 
Dim Scrpt as string

sc = createObject("MSScriptControl.ScriptControl")

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)

With SC 
.Language = "VBScript" 
.UseSafeSubset = False 
.AllowUI = True 
End With


sc.addcode(Scrpt)


End Sub

End Class

Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.

/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.

/win32manifest: The provided file is embedded in the manifest section of the output PE.

In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.

The command line

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"

The manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
  <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 
  manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" 
  processorArchitecture="*" name="VBS2EXE" type="win32" /> 
  <description>Script to Exe</description> 
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 
  <security> <requestedPrivileges> 
  <requestedExecutionLevel level="requireAdministrator" 
  uiAccess="false" /> </requestedPrivileges> 
  </security> </trustInfo> </assembly>

Hopefully it will now ONLY run as admin.

Give Access To a Host's Objects

Here's an example giving the vbscript access to a .NET object.

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub 

Public Sub New() 

InitializeComponent() 

End Sub 

Public Shared Sub Main() 

Dim sc as object
Dim Scrpt as string 

sc = createObject("MSScriptControl.ScriptControl") 

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state" 

With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With 


sc.addcode(Scrpt) 


End Sub 

End Class 

To Embed version info

Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.

Download ResHacker from http://www.angusj.com/resourcehacker

Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.

Type

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"

Ansible: Store command's stdout in new variable?

If you want to go further and extract the exact information you want from the Playbook results, use JSON query language like jmespath, an example:

  - name: Sample Playbook
    // Fill up your task
    no_log: True
    register: example_output

  - name: Json Query
    set_fact:
      query_result:
        example_output:"{{ example_output | json_query('results[*].name') }}"

How can I use interface as a C# generic type constraint?

For some time now I've been thinking about near-compile-time constraints, so this is a perfect opportunity to launch the concept.

The basic idea is that if you cannot do a check compile time, you should do it at the earliest possible point in time, which is basically the moment the application starts. If all checks are okay, the application will run; if a check fails, the application will fail instantly.

Behavior

The best possible outcome is that our program doesn't compile if the constraints are not met. Unfortunately that's not possible in the current C# implementation.

Next best thing is that the program crashes the moment it's started.

The last option is that the program will crash the moment the code is hit. This is the default behavior of .NET. For me, this is completely unacceptable.

Prerequirements

We need to have a constraint mechanism, so for the lack of anything better... let's use an attribute. The attribute will be present on top of a generic constraint to check if it matches our conditions. If it doesn't, we give an ugly error.

This enables us to do things like this in our code:

public class Clas<[IsInterface] T> where T : class

(I've kept the where T:class here, because I always prefer compile-time checks to run-time checks)

So, that only leaves us with 1 problem, which is checking if all the types that we use match the constraint. How hard can it be?

Let's break it up

Generic types are always either on a class (/struct/interface) or on a method.

Triggering a constraint requires you to do one of the following things:

  1. Compile-time, when using a type in a type (inheritance, generic constraint, class member)
  2. Compile-time, when using a type in a method body
  3. Run-time, when using reflection to construct something based on the generic base class.
  4. Run-time, when using reflection to construct something based on RTTI.

At this point, I would like to state that you should always avoid doing (4) in any program IMO. Regardless, these checks won't support it, since it would effectively mean solving the halting problem.

Case 1: using a type

Example:

public class TestClass : SomeClass<IMyInterface> { ... } 

Example 2:

public class TestClass 
{ 
    SomeClass<IMyInterface> myMember; // or a property, method, etc.
} 

Basically this involves scanning all types, inheritance, members, parameters, etc, etc, etc. If a type is a generic type and has a constraint, we check the constraint; if it's an array, we check the element type.

At this point I must add that this will break the fact that by default .NET loads types 'lazy'. By scanning all the types, we force the .NET runtime to load them all. For most programs this shouldn't be a problem; still, if you use static initializers in your code, you might encounter problems with this approach... That said, I wouldn't advice anyone to do this anyways (except for things like this :-), so it shouldn't give you a lot of problems.

Case 2: using a type in a method

Example:

void Test() {
    new SomeClass<ISomeInterface>();
}

To check this we have only 1 option: decompile the class, check all member tokens that are used and if one of them is the generic type - check the arguments.

Case 3: Reflection, runtime generic construction

Example:

typeof(CtorTest<>).MakeGenericType(typeof(IMyInterface))

I suppose it's theoretically possible to check this with similar tricks as case (2), but the implementation of it is much harder (you need to check if MakeGenericType is called in some code path). I won't go into details here...

Case 4: Reflection, runtime RTTI

Example:

Type t = Type.GetType("CtorTest`1[IMyInterface]");

This is the worst case scenario and as I explained before generally a bad idea IMHO. Either way, there's no practical way to figure this out using checks.

Testing the lot

Creating a program that tests case (1) and (2) will result in something like this:

[AttributeUsage(AttributeTargets.GenericParameter)]
public class IsInterface : ConstraintAttribute
{
    public override bool Check(Type genericType)
    {
        return genericType.IsInterface;
    }

    public override string ToString()
    {
        return "Generic type is not an interface";
    }
}

public abstract class ConstraintAttribute : Attribute
{
    public ConstraintAttribute() {}

    public abstract bool Check(Type generic);
}

internal class BigEndianByteReader
{
    public BigEndianByteReader(byte[] data)
    {
        this.data = data;
        this.position = 0;
    }

    private byte[] data;
    private int position;

    public int Position
    {
        get { return position; }
    }

    public bool Eof
    {
        get { return position >= data.Length; }
    }

    public sbyte ReadSByte()
    {
        return (sbyte)data[position++];
    }

    public byte ReadByte()
    {
        return (byte)data[position++];
    }

    public int ReadInt16()
    {
        return ((data[position++] | (data[position++] << 8)));
    }

    public ushort ReadUInt16()
    {
        return (ushort)((data[position++] | (data[position++] << 8)));
    }

    public int ReadInt32()
    {
        return (((data[position++] | (data[position++] << 8)) | (data[position++] << 0x10)) | (data[position++] << 0x18));
    }

    public ulong ReadInt64()
    {
        return (ulong)(((data[position++] | (data[position++] << 8)) | (data[position++] << 0x10)) | (data[position++] << 0x18) | 
                        (data[position++] << 0x20) | (data[position++] << 0x28) | (data[position++] << 0x30) | (data[position++] << 0x38));
    }

    public double ReadDouble()
    {
        var result = BitConverter.ToDouble(data, position);
        position += 8;
        return result;
    }

    public float ReadSingle()
    {
        var result = BitConverter.ToSingle(data, position);
        position += 4;
        return result;
    }
}

internal class ILDecompiler
{
    static ILDecompiler()
    {
        // Initialize our cheat tables
        singleByteOpcodes = new OpCode[0x100];
        multiByteOpcodes = new OpCode[0x100];

        FieldInfo[] infoArray1 = typeof(OpCodes).GetFields();
        for (int num1 = 0; num1 < infoArray1.Length; num1++)
        {
            FieldInfo info1 = infoArray1[num1];
            if (info1.FieldType == typeof(OpCode))
            {
                OpCode code1 = (OpCode)info1.GetValue(null);
                ushort num2 = (ushort)code1.Value;
                if (num2 < 0x100)
                {
                    singleByteOpcodes[(int)num2] = code1;
                }
                else
                {
                    if ((num2 & 0xff00) != 0xfe00)
                    {
                        throw new Exception("Invalid opcode: " + num2.ToString());
                    }
                    multiByteOpcodes[num2 & 0xff] = code1;
                }
            }
        }
    }

    private ILDecompiler() { }

    private static OpCode[] singleByteOpcodes;
    private static OpCode[] multiByteOpcodes;

    public static IEnumerable<ILInstruction> Decompile(MethodBase mi, byte[] ildata)
    {
        Module module = mi.Module;

        BigEndianByteReader reader = new BigEndianByteReader(ildata);
        while (!reader.Eof)
        {
            OpCode code = OpCodes.Nop;

            int offset = reader.Position;
            ushort b = reader.ReadByte();
            if (b != 0xfe)
            {
                code = singleByteOpcodes[b];
            }
            else
            {
                b = reader.ReadByte();
                code = multiByteOpcodes[b];
                b |= (ushort)(0xfe00);
            }

            object operand = null;
            switch (code.OperandType)
            {
                case OperandType.InlineBrTarget:
                    operand = reader.ReadInt32() + reader.Position;
                    break;
                case OperandType.InlineField:
                    if (mi is ConstructorInfo)
                    {
                        operand = module.ResolveField(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
                    }
                    else
                    {
                        operand = module.ResolveField(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
                    }
                    break;
                case OperandType.InlineI:
                    operand = reader.ReadInt32();
                    break;
                case OperandType.InlineI8:
                    operand = reader.ReadInt64();
                    break;
                case OperandType.InlineMethod:
                    try
                    {
                        if (mi is ConstructorInfo)
                        {
                            operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
                        }
                        else
                        {
                            operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
                        }
                    }
                    catch
                    {
                        operand = null;
                    }
                    break;
                case OperandType.InlineNone:
                    break;
                case OperandType.InlineR:
                    operand = reader.ReadDouble();
                    break;
                case OperandType.InlineSig:
                    operand = module.ResolveSignature(reader.ReadInt32());
                    break;
                case OperandType.InlineString:
                    operand = module.ResolveString(reader.ReadInt32());
                    break;
                case OperandType.InlineSwitch:
                    int count = reader.ReadInt32();
                    int[] targetOffsets = new int[count];
                    for (int i = 0; i < count; ++i)
                    {
                        targetOffsets[i] = reader.ReadInt32();
                    }
                    int pos = reader.Position;
                    for (int i = 0; i < count; ++i)
                    {
                        targetOffsets[i] += pos;
                    }
                    operand = targetOffsets;
                    break;
                case OperandType.InlineTok:
                case OperandType.InlineType:
                    try
                    {
                        if (mi is ConstructorInfo)
                        {
                            operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
                        }
                        else
                        {
                            operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
                        }
                    }
                    catch
                    {
                        operand = null;
                    }
                    break;
                case OperandType.InlineVar:
                    operand = reader.ReadUInt16();
                    break;
                case OperandType.ShortInlineBrTarget:
                    operand = reader.ReadSByte() + reader.Position;
                    break;
                case OperandType.ShortInlineI:
                    operand = reader.ReadSByte();
                    break;
                case OperandType.ShortInlineR:
                    operand = reader.ReadSingle();
                    break;
                case OperandType.ShortInlineVar:
                    operand = reader.ReadByte();
                    break;

                default:
                    throw new Exception("Unknown instruction operand; cannot continue. Operand type: " + code.OperandType);
            }

            yield return new ILInstruction(offset, code, operand);
        }
    }
}

public class ILInstruction
{
    public ILInstruction(int offset, OpCode code, object operand)
    {
        this.Offset = offset;
        this.Code = code;
        this.Operand = operand;
    }

    public int Offset { get; private set; }
    public OpCode Code { get; private set; }
    public object Operand { get; private set; }
}

public class IncorrectConstraintException : Exception
{
    public IncorrectConstraintException(string msg, params object[] arg) : base(string.Format(msg, arg)) { }
}

public class ConstraintFailedException : Exception
{
    public ConstraintFailedException(string msg) : base(msg) { }
    public ConstraintFailedException(string msg, params object[] arg) : base(string.Format(msg, arg)) { }
}

public class NCTChecks
{
    public NCTChecks(Type startpoint)
        : this(startpoint.Assembly)
    { }

    public NCTChecks(params Assembly[] ass)
    {
        foreach (var assembly in ass)
        {
            assemblies.Add(assembly);

            foreach (var type in assembly.GetTypes())
            {
                EnsureType(type);
            }
        }

        while (typesToCheck.Count > 0)
        {
            var t = typesToCheck.Pop();
            GatherTypesFrom(t);

            PerformRuntimeCheck(t);
        }
    }

    private HashSet<Assembly> assemblies = new HashSet<Assembly>();

    private Stack<Type> typesToCheck = new Stack<Type>();
    private HashSet<Type> typesKnown = new HashSet<Type>();

    private void EnsureType(Type t)
    {
        // Don't check for assembly here; we can pass f.ex. System.Lazy<Our.T<MyClass>>
        if (t != null && !t.IsGenericTypeDefinition && typesKnown.Add(t))
        {
            typesToCheck.Push(t);

            if (t.IsGenericType)
            {
                foreach (var par in t.GetGenericArguments())
                {
                    EnsureType(par);
                }
            }

            if (t.IsArray)
            {
                EnsureType(t.GetElementType());
            }
        }

    }

    private void PerformRuntimeCheck(Type t)
    {
        if (t.IsGenericType && !t.IsGenericTypeDefinition)
        {
            // Only check the assemblies we explicitly asked for:
            if (this.assemblies.Contains(t.Assembly))
            {
                // Gather the generics data:
                var def = t.GetGenericTypeDefinition();
                var par = def.GetGenericArguments();
                var args = t.GetGenericArguments();

                // Perform checks:
                for (int i = 0; i < args.Length; ++i)
                {
                    foreach (var check in par[i].GetCustomAttributes(typeof(ConstraintAttribute), true).Cast<ConstraintAttribute>())
                    {
                        if (!check.Check(args[i]))
                        {
                            string error = "Runtime type check failed for type " + t.ToString() + ": " + check.ToString();

                            Debugger.Break();
                            throw new ConstraintFailedException(error);
                        }
                    }
                }
            }
        }
    }

    // Phase 1: all types that are referenced in some way
    private void GatherTypesFrom(Type t)
    {
        EnsureType(t.BaseType);

        foreach (var intf in t.GetInterfaces())
        {
            EnsureType(intf);
        }

        foreach (var nested in t.GetNestedTypes())
        {
            EnsureType(nested);
        }

        var all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
        foreach (var field in t.GetFields(all))
        {
            EnsureType(field.FieldType);
        }
        foreach (var property in t.GetProperties(all))
        {
            EnsureType(property.PropertyType);
        }
        foreach (var evt in t.GetEvents(all))
        {
            EnsureType(evt.EventHandlerType);
        }
        foreach (var ctor in t.GetConstructors(all))
        {
            foreach (var par in ctor.GetParameters())
            {
                EnsureType(par.ParameterType);
            }

            // Phase 2: all types that are used in a body
            GatherTypesFrom(ctor);
        }
        foreach (var method in t.GetMethods(all))
        {
            if (method.ReturnType != typeof(void))
            {
                EnsureType(method.ReturnType);
            }

            foreach (var par in method.GetParameters())
            {
                EnsureType(par.ParameterType);
            }

            // Phase 2: all types that are used in a body
            GatherTypesFrom(method);
        }
    }

    private void GatherTypesFrom(MethodBase method)
    {
        if (this.assemblies.Contains(method.DeclaringType.Assembly)) // only consider methods we've build ourselves
        {
            MethodBody methodBody = method.GetMethodBody();
            if (methodBody != null)
            {
                // Handle local variables
                foreach (var local in methodBody.LocalVariables)
                {
                    EnsureType(local.LocalType);
                }

                // Handle method body
                var il = methodBody.GetILAsByteArray();
                if (il != null)
                {
                    foreach (var oper in ILDecompiler.Decompile(method, il))
                    {
                        if (oper.Operand is MemberInfo)
                        {
                            foreach (var type in HandleMember((MemberInfo)oper.Operand))
                            {
                                EnsureType(type);
                            }

                        }
                    }
                }
            }
        }
    }

    private static IEnumerable<Type> HandleMember(MemberInfo info)
    {
        // Event, Field, Method, Constructor or Property.
        yield return info.DeclaringType;
        if (info is EventInfo)
        {
            yield return ((EventInfo)info).EventHandlerType;
        }
        else if (info is FieldInfo)
        {
            yield return ((FieldInfo)info).FieldType;
        }
        else if (info is PropertyInfo)
        {
            yield return ((PropertyInfo)info).PropertyType;
        }
        else if (info is ConstructorInfo)
        {
            foreach (var par in ((ConstructorInfo)info).GetParameters())
            {
                yield return par.ParameterType;
            }
        }
        else if (info is MethodInfo)
        {
            foreach (var par in ((MethodInfo)info).GetParameters())
            {
                yield return par.ParameterType;
            }
        }
        else if (info is Type)
        {
            yield return (Type)info;
        }
        else
        {
            throw new NotSupportedException("Incorrect unsupported member type: " + info.GetType().Name);
        }
    }
}

Using the code

Well, that's the easy part :-)

// Create something illegal
public class Bar2 : IMyInterface
{
    public void Execute()
    {
        throw new NotImplementedException();
    }
}

// Our fancy check
public class Foo<[IsInterface] T>
{
}

class Program
{
    static Program()
    {
        // Perform all runtime checks
        new NCTChecks(typeof(Program));
    }

    static void Main(string[] args)
    {
        // Normal operation
        Console.WriteLine("Foo");
        Console.ReadLine();
    }
}

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home') in your URL patterns.

The solution is to update your urls.py to include the view callable. This means that you have to import the view in your urls.py. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.

from django.conf.urls import include, url

from django.contrib.auth.views import login
from myapp.views import home, contact

urlpatterns = [
    url(r'^$', home, name='home'),
    url(r'^contact/$', contact, name='contact'),
    url(r'^login/$', login, name='login'),
]

If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.

from django.conf.urls import include, url

from django.contrib.auth import views as auth_views
from myapp import views as myapp_views

urlpatterns = [
    url(r'^$', myapp_views.home, name='home'),
    url(r'^contact/$', myapp_views.contact, name='contact'),
    url(r'^login/$', auth_views.login, name='login'),
]

Note that we have used as myapp_views and as auth_views, which allows us to import the views.py from multiple apps without them clashing.

See the Django URL dispatcher docs for more information about urlpatterns.

Copy directory to another directory using ADD command

You can use COPY. You need to specify the directory explicitly. It won't be created by itself

COPY go /usr/local/go

Reference: Docker CP reference

How to kill MySQL connections

In MySQL Workbench:

Left-hand side navigator > Management > Client Connections

It gives you the option to kill queries and connections.

Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here

Iterate over object in Angular

If you have es6-shim or your tsconfig.json target es6, you could use ES6 Map to make it.

var myDict = new Map();
myDict.set('key1','value1');
myDict.set('key2','value2');

<div *ngFor="let keyVal of myDict.entries()">
    key:{{keyVal[0]}}, val:{{keyVal[1]}}
</div>

In WPF, what are the differences between the x:Name and Name attributes?

Name can also be set using property element syntax with inner text, but that is uncommon. In contrast, x:Name cannot be set in XAML property element syntax, or in code using SetValue; it can only be set using attribute syntax on objects because it is a directive.
If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but a parse exception will result if both are specified on the same element. If the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.

Merge two dataframes by index

you can use concat([df1, df2, ...], axis=1) in order to concatenate two or more DFs aligned by indexes:

pd.concat([df1, df2, df3, ...], axis=1)

or merge for concatenating by custom fields / indexes:

# join by _common_ columns: `col1`, `col3`
pd.merge(df1, df2, on=['col1','col3'])

# join by: `df1.col1 == df2.index`
pd.merge(df1, df2, left_on='col1' right_index=True)

or join for joining by index:

 df1.join(df2)

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

How to set a Timer in Java?

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

How to find the .NET framework version of a Visual Studio project?

You can also search the Visual Studio project files for the XML tag RequiredTargetFramework. This tag seems to exist on .NET 3.5 and higher.

For example: <RequiredTargetFramework>3.5</RequiredTargetFramework>

How to add a hook to the application context initialization event?

Since Spring 4.2 you can use @EventListener (documentation)

@Component
class MyClassWithEventListeners {

    @EventListener({ContextRefreshedEvent.class})
    void contextRefreshedEvent() {
        System.out.println("a context refreshed event happened");
    }
}

java.util.Date to XMLGregorianCalendar

I hope my encoding here is right ;D To make it faster just use the ugly getInstance() call of GregorianCalendar instead of constructor call:

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class DateTest {

   public static void main(final String[] args) throws Exception {
      // do not forget the type cast :/
      GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
      XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gcal);
      System.out.println(xgcal);
   }

}

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

Using Python's list index() method on a list of tuples or objects?

Those list comprehensions are messy after a while.

I like this Pythonic approach:

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

If you need your code to be all super performant:

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

C# Sort and OrderBy comparison

I just want to add that orderby is way more useful.

Why? Because I can do this:

Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)

Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.

Very easy.

I can't do that with sort. I wonder why. Do fine with orderBy.

As for speed it's always O(n).

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

HTML iframe - disable scroll

Add this styles..for your iframe tag..

overflow-x:hidden;
overflow-y:hidden;

How to print a float with 2 decimal places in Java?

You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.

When does a process get SIGABRT (signal 6)?

There's another simple cause in case of c++.

std::thread::~thread{
    if((joinable ())
        std::terminate ();
}

i.e. scope of thread ended but you forgot to call either

thread::join();

or

thread::detach();

How to open Console window in Eclipse?

Window > Perspective > Reset Perspective

Reverse colormap in matplotlib

There are two types of LinearSegmentedColormaps. In some, the _segmentdata is given explicitly, e.g., for jet:

>>> cm.jet._segmentdata
{'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1, 0, 0)), 'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1, 0, 0))}

For rainbow, _segmentdata is given as follows:

>>> cm.rainbow._segmentdata
{'blue': <function <lambda> at 0x7fac32ac2b70>, 'red': <function <lambda> at 0x7fac32ac7840>, 'green': <function <lambda> at 0x7fac32ac2d08>}

We can find the functions in the source of matplotlib, where they are given as

_rainbow_data = {
        'red': gfunc[33],   # 33: lambda x: np.abs(2 * x - 0.5),
        'green': gfunc[13], # 13: lambda x: np.sin(x * np.pi),
        'blue': gfunc[10],  # 10: lambda x: np.cos(x * np.pi / 2)
}

Everything you want is already done in matplotlib, just call cm.revcmap, which reverses both types of segmentdata, so

cm.revcmap(cm.rainbow._segmentdata)

should do the job - you can simply create a new LinearSegmentData from that. In revcmap, the reversal of function based SegmentData is done with

def _reverser(f):
    def freversed(x):
        return f(1 - x)
    return freversed

while the other lists are reversed as usual

valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] 

So actually the whole thing you want, is

def reverse_colourmap(cmap, name = 'my_cmap_r'):
     return mpl.colors.LinearSegmentedColormap(name, cm.revcmap(cmap._segmentdata)) 

Better way to set distance between flexbox items

Here's my solution, that doesn't require setting any classes on the child elements:

.flex-inline-row {
    display: inline-flex;
    flex-direction: row;
}

.flex-inline-row.flex-spacing-4px > :not(:last-child) {
    margin-right: 4px;
}

Usage:

<div class="flex-inline-row flex-spacing-4px">
  <span>Testing</span>
  <span>123</span>
</div>

The same technique can be used for normal flex rows and columns in addition to the inline example given above, and extended with classes for spacing other than 4px.

Can you do greater than comparison on a date in a Rails 3 search?

Note.
  where(:user_id => current_user.id, :notetype => p[:note_type]).
  where("date > ?", p[:date]).
  order('date ASC, created_at ASC')

or you can also convert everything into the SQL notation

Note.
  where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
  order('date ASC, created_at ASC')

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How do I count the number of rows and columns in a file using bash?

If your file is big but you are certain that the number of columns remains the same for each row (and you have no heading) use:

head -n 1 FILE | awk '{print NF}'

to find the number of columns, where FILE is your file name.

To find the number of lines 'wc -l FILE' will work.

CSS Flex Box Layout: full-width row and columns

Just use another container to wrap last two divs. Don't forget to use CSS prefixes.

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
   display: flex;_x000D_
   flex-direction: column;_x000D_
   height: 600px;_x000D_
   width: 580px;_x000D_
   background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
   height: 100px;_x000D_
   background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
   display: flex;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
   background-color: red;_x000D_
   flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
   background-color: blue;_x000D_
   flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
   <div id="productShowcaseTitle">1</div>_x000D_
   <div id="anotherContainer">_x000D_
      <div id="productShowcaseDetail">2</div>_x000D_
      <div id="productShowcaseThumbnailContainer">3</div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adding to a vector of pair

revenue.pushback("string",map[i].second);

But that says cannot take two arguments. So how can I add to this vector pair?

You're on the right path, but think about it; what does your vector hold? It certainly doesn't hold a string and an int in one position, it holds a Pair. So...

revenue.push_back( std::make_pair( "string", map[i].second ) );     

If statement in select (ORACLE)

In one line, answer is as below;

[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]

Why does typeof array with objects return "object" and not "array"?

Quoting the spec

15.4 Array Objects

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

And here's a table for typeof

enter image description here


To add some background, there are two data types in JavaScript:

  1. Primitive Data types - This includes null, undefined, string, boolean, number and object.
  2. Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.

An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.

An array can be considered to be an object with the following properties/keys:

  1. Length - This can be 0 or above (non-negative).
  2. The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.

Hope this helped shed more light on why typeof Array returns an object. Cheers!

Case-insensitive search in Rails model

You can also use scopes like this below and put them in a concern and include in models you may need them:

scope :ci_find, lambda { |column, value| where("lower(#{column}) = ?", value.downcase).first }

Then use like this: Model.ci_find('column', 'value')

Reset Windows Activation/Remove license key

  1. Open a command prompt as an Administrator.

  2. Enter slmgr /upk and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.

  3. Enter slmgr /cpky and wait for this to complete. This will remove the product key from the registry if it's still there.

  4. Enter slmgr /rearm and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.

This should put the system back to a pre-key state.

Hope this helps you out!

Not connecting to SQL Server over VPN

I have this issue a lot with Citrix Access Gateway. I usually get a timeout error. If you are able to connect to the database from a client on the network, but not from a remote client via VPN, you can forget most suggestions given here, because they all address server-side issues.

I am able to connect when I increase the timeout from the default (15 seconds) to 60 seconds, and for good measure, force the protocol to TCP/IP. These things can be done on the Options screen of the login dialog:

`

How can I analyze a heap dump in IntelliJ? (memory leak)

You can also use VisualVM Launcher to launch VisualVM from within IDEA. https://plugins.jetbrains.com/plugin/7115?pr=idea I personally find this more convenient.

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Replace or delete certain characters from filenames of all files in a folder

I would recommend the rename command for this. Type ren /? at the command line for more help.

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

I will just give the analogy with which I understand memory consistency models (or memory models, for short). It is inspired by Leslie Lamport's seminal paper "Time, Clocks, and the Ordering of Events in a Distributed System". The analogy is apt and has fundamental significance, but may be overkill for many people. However, I hope it provides a mental image (a pictorial representation) that facilitates reasoning about memory consistency models.

Let’s view the histories of all memory locations in a space-time diagram in which the horizontal axis represents the address space (i.e., each memory location is represented by a point on that axis) and the vertical axis represents time (we will see that, in general, there is not a universal notion of time). The history of values held by each memory location is, therefore, represented by a vertical column at that memory address. Each value change is due to one of the threads writing a new value to that location. By a memory image, we will mean the aggregate/combination of values of all memory locations observable at a particular time by a particular thread.

Quoting from "A Primer on Memory Consistency and Cache Coherence"

The intuitive (and most restrictive) memory model is sequential consistency (SC) in which a multithreaded execution should look like an interleaving of the sequential executions of each constituent thread, as if the threads were time-multiplexed on a single-core processor.

That global memory order can vary from one run of the program to another and may not be known beforehand. The characteristic feature of SC is the set of horizontal slices in the address-space-time diagram representing planes of simultaneity (i.e., memory images). On a given plane, all of its events (or memory values) are simultaneous. There is a notion of Absolute Time, in which all threads agree on which memory values are simultaneous. In SC, at every time instant, there is only one memory image shared by all threads. That's, at every instant of time, all processors agree on the memory image (i.e., the aggregate content of memory). Not only does this imply that all threads view the same sequence of values for all memory locations, but also that all processors observe the same combinations of values of all variables. This is the same as saying all memory operations (on all memory locations) are observed in the same total order by all threads.

In relaxed memory models, each thread will slice up address-space-time in its own way, the only restriction being that slices of each thread shall not cross each other because all threads must agree on the history of every individual memory location (of course, slices of different threads may, and will, cross each other). There is no universal way to slice it up (no privileged foliation of address-space-time). Slices do not have to be planar (or linear). They can be curved and this is what can make a thread read values written by another thread out of the order they were written in. Histories of different memory locations may slide (or get stretched) arbitrarily relative to each other when viewed by any particular thread. Each thread will have a different sense of which events (or, equivalently, memory values) are simultaneous. The set of events (or memory values) that are simultaneous to one thread are not simultaneous to another. Thus, in a relaxed memory model, all threads still observe the same history (i.e., sequence of values) for each memory location. But they may observe different memory images (i.e., combinations of values of all memory locations). Even if two different memory locations are written by the same thread in sequence, the two newly written values may be observed in different order by other threads.

[Picture from Wikipedia] Picture from Wikipedia

Readers familiar with Einstein’s Special Theory of Relativity will notice what I am alluding to. Translating Minkowski’s words into the memory models realm: address space and time are shadows of address-space-time. In this case, each observer (i.e., thread) will project shadows of events (i.e., memory stores/loads) onto his own world-line (i.e., his time axis) and his own plane of simultaneity (his address-space axis). Threads in the C++11 memory model correspond to observers that are moving relative to each other in special relativity. Sequential consistency corresponds to the Galilean space-time (i.e., all observers agree on one absolute order of events and a global sense of simultaneity).

The resemblance between memory models and special relativity stems from the fact that both define a partially-ordered set of events, often called a causal set. Some events (i.e., memory stores) can affect (but not be affected by) other events. A C++11 thread (or observer in physics) is no more than a chain (i.e., a totally ordered set) of events (e.g., memory loads and stores to possibly different addresses).

In relativity, some order is restored to the seemingly chaotic picture of partially ordered events, since the only temporal ordering that all observers agree on is the ordering among “timelike” events (i.e., those events that are in principle connectible by any particle going slower than the speed of light in a vacuum). Only the timelike related events are invariantly ordered. Time in Physics, Craig Callender.

In C++11 memory model, a similar mechanism (the acquire-release consistency model) is used to establish these local causality relations.

To provide a definition of memory consistency and a motivation for abandoning SC, I will quote from "A Primer on Memory Consistency and Cache Coherence"

For a shared memory machine, the memory consistency model defines the architecturally visible behavior of its memory system. The correctness criterion for a single processor core partitions behavior between “one correct result” and “many incorrect alternatives”. This is because the processor’s architecture mandates that the execution of a thread transforms a given input state into a single well-defined output state, even on an out-of-order core. Shared memory consistency models, however, concern the loads and stores of multiple threads and usually allow many correct executions while disallowing many (more) incorrect ones. The possibility of multiple correct executions is due to the ISA allowing multiple threads to execute concurrently, often with many possible legal interleavings of instructions from different threads.

Relaxed or weak memory consistency models are motivated by the fact that most memory orderings in strong models are unnecessary. If a thread updates ten data items and then a synchronization flag, programmers usually do not care if the data items are updated in order with respect to each other but only that all data items are updated before the flag is updated (usually implemented using FENCE instructions). Relaxed models seek to capture this increased ordering flexibility and preserve only the orders that programmers “require” to get both higher performance and correctness of SC. For example, in certain architectures, FIFO write buffers are used by each core to hold the results of committed (retired) stores before writing the results to the caches. This optimization enhances performance but violates SC. The write buffer hides the latency of servicing a store miss. Because stores are common, being able to avoid stalling on most of them is an important benefit. For a single-core processor, a write buffer can be made architecturally invisible by ensuring that a load to address A returns the value of the most recent store to A even if one or more stores to A are in the write buffer. This is typically done by either bypassing the value of the most recent store to A to the load from A, where “most recent” is determined by program order, or by stalling a load of A if a store to A is in the write buffer. When multiple cores are used, each will have its own bypassing write buffer. Without write buffers, the hardware is SC, but with write buffers, it is not, making write buffers architecturally visible in a multicore processor.

Store-store reordering may happen if a core has a non-FIFO write buffer that lets stores depart in a different order than the order in which they entered. This might occur if the first store misses in the cache while the second hits or if the second store can coalesce with an earlier store (i.e., before the first store). Load-load reordering may also happen on dynamically-scheduled cores that execute instructions out of program order. That can behave the same as reordering stores on another core (Can you come up with an example interleaving between two threads?). Reordering an earlier load with a later store (a load-store reordering) can cause many incorrect behaviors, such as loading a value after releasing the lock that protects it (if the store is the unlock operation). Note that store-load reorderings may also arise due to local bypassing in the commonly implemented FIFO write buffer, even with a core that executes all instructions in program order.

Because cache coherence and memory consistency are sometimes confused, it is instructive to also have this quote:

Unlike consistency, cache coherence is neither visible to software nor required. Coherence seeks to make the caches of a shared-memory system as functionally invisible as the caches in a single-core system. Correct coherence ensures that a programmer cannot determine whether and where a system has caches by analyzing the results of loads and stores. This is because correct coherence ensures that the caches never enable new or different functional behavior (programmers may still be able to infer likely cache structure using timing information). The main purpose of cache coherence protocols is maintaining the single-writer-multiple-readers (SWMR) invariant for every memory location. An important distinction between coherence and consistency is that coherence is specified on a per-memory location basis, whereas consistency is specified with respect to all memory locations.

Continuing with our mental picture, the SWMR invariant corresponds to the physical requirement that there be at most one particle located at any one location but there can be an unlimited number of observers of any location.

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

From an array of objects, extract value of a property as array

While map is a proper solution to select 'columns' from a list of objects, it has a downside. If not explicitly checked whether or not the columns exists, it'll throw an error and (at best) provide you with undefined. I'd opt for a reduce solution, which can simply ignore the property or even set you up with a default value.

function getFields(list, field) {
    //  reduce the provided list to an array only containing the requested field
    return list.reduce(function(carry, item) {
        //  check if the item is actually an object and does contain the field
        if (typeof item === 'object' && field in item) {
            carry.push(item[field]);
        }

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin example

This would work even if one of the items in the provided list is not an object or does not contain the field.

It can even be made more flexible by negotiating a default value should an item not be an object or not contain the field.

function getFields(list, field, otherwise) {
    //  reduce the provided list to an array containing either the requested field or the alternative value
    return list.reduce(function(carry, item) {
        //  If item is an object and contains the field, add its value and the value of otherwise if not
        carry.push(typeof item === 'object' && field in item ? item[field] : otherwise);

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin example

This would be the same with map, as the length of the returned array would be the same as the provided array. (In which case a map is slightly cheaper than a reduce):

function getFields(list, field, otherwise) {
    //  map the provided list to an array containing either the requested field or the alternative value
    return list.map(function(item) {
        //  If item is an object and contains the field, add its value and the value of otherwise if not
        return typeof item === 'object' && field in item ? item[field] : otherwise;
    }, []);
}

jsbin example

And then there is the most flexible solution, one which lets you switch between both behaviours simply by providing an alternative value.

function getFields(list, field, otherwise) {
    //  determine once whether or not to use the 'otherwise'
    var alt = typeof otherwise !== 'undefined';

    //  reduce the provided list to an array only containing the requested field
    return list.reduce(function(carry, item) {
        //  If item is an object and contains the field, add its value and the value of 'otherwise' if it was provided
        if (typeof item === 'object' && field in item) {
            carry.push(item[field]);
        }
        else if (alt) {
            carry.push(otherwise);
        }

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin example

As the examples above (hopefully) shed some light on the way this works, lets shorten the function a bit by utilising the Array.concat function.

function getFields(list, field, otherwise) {
    var alt = typeof otherwise !== 'undefined';

    return list.reduce(function(carry, item) {
        return carry.concat(typeof item === 'object' && field in item ? item[field] : (alt ? otherwise : []));
    }, []);
}

jsbin example

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Open Virtual Box. Select your virtual Android Device and click on Settings.

enter image description here

Select Network.

enter image description here

Make sure "Enable Network Adapter" box is checked. Also Make sure "Attached to:" has "Host-only Adapter selected". Note the name of the adapter.

enter image description here

Open Settings and click on "Network & Internet"

enter image description here

In the window that opens click on "Change Adapter Options"

enter image description here

In the window that opens you can find many Network names listed. Find the network name that matches with the network name that you noted earlier in the Virtual Box.

enter image description here

Note if that network is Enabled or Disabled.

If the network is Disabled, right click and click Enable.

If the network is Enabled, right click, click Disable and then again click Enable.

enter image description here

Close the window, open Genymotion and start your Virtual Device. The device should now boot without any error.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Ideally you'd do this:

<a href="javascriptlessDestination.html" onclick="myJSFunc(); return false;">Link text</a>

Or, even better, you'd have the default action link in the HTML, and you'd add the onclick event to the element unobtrusively via JavaScript after the DOM renders, thus ensuring that if JavaScript is not present/utilized you don't have useless event handlers riddling your code and potentially obfuscating (or at least distracting from) your actual content.

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I use below code after js file include and it's working now.

<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
            jQuery.browser.msie = true;
            jQuery.browser.version = RegExp.$1;
        }
    })();
</script>

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Video auto play is not working in Safari and Chrome desktop browser

It happens that Safari and Chrome on Desktop do not like DOM manipulation around the video tag. They will not fire the play order when the autoplay attribute is set even if the canplaythrough event has fired when the DOM around the video tag has changed after initial page load. Basically I had the same issue until I deleted a .wrap() jQuery around the video tag and after that it autoplayed as expected.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

How do I configure the proxy settings so that Eclipse can download new plugins?

There is an eclipse.ini (sts.ini) parameter that can help:

-Djava.net.useSystemProxies=true

A lot of effort wasted on this trivial setting each time I change the work environment... See one of the related bugs on eclipse bugzilla.

How to disable margin-collapsing?

For your information you could use grid but with side effects :)

.parent {
  display: grid
}

Append data frames together in a for loop

You should try this:

df_total = data.frame()
for (i in 1:7){
    # vector output
    model <- #some processing

    # add vector to a dataframe
    df <- data.frame(model)
    df_total <- rbind(df_total,df)
}

Custom ImageView with drop shadow

I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..

 private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);

// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
    int shadowThickness = 13; // can be adjusted as needed
    int bmpOriginalWidth = origBitmap.getWidth();
    int bmpOriginalHeight = origBitmap.getHeight();
    int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
    int bigH = bmpOriginalHeight + shadowThickness * 2;
    Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
    Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
    //right shade - direction of gradient is positive x (width)
    Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(rightShader);
    canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
    //bottom shade - direction is positive y (height)
    Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(bottomShader);
    canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
    //left shade - direction is negative x
    Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(leftShader);
    canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
    //top shade - direction is negative y
    Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(topShader);
    canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
    // starting to draw bitmap not from 0,0 to get margins for shade rectangles
    canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
    return containerBitmap;
}

Change the color in the const as you see fit.

Swing vs JavaFx for desktop applications

I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul.

Also, SWT is actually newer and more actively maintained than Swing. (It was originally developed as a replacement for Swing using native components).

Convert Decimal to Varchar

Hope this will help .

DECLARE  @emp_cond nvarchar(Max) =' ',@LOCATION_ID  NUMERIC(18,0)   
SET@LOCATION_ID=10110000000
IF CAST(@LOCATION_ID AS VARCHAR(18))<>' ' 
            BEGIN
                SELECT @emp_cond= @emp_cond + N' AND 
CM.STATIC_EMP_INFO.EMP_ID = ' ' '+  CAST(@LOCATION_ID AS VARCHAR(18))  +' ' ' '
           END
print  @emp_cond  
EXEC( @emp_cond) 

Add and remove a class on click using jQuery?

Here is an article with live working demo Class Animation In JQuery

You can try this,

$(function () {
   $("#btnSubmit").click(function () {
   $("#btnClass").removeClass("btnDiv").addClass("btn");
   });
});

you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.

$(function () {
        $("#btnSubmit").click(function () {
            $("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
        });
    });

Yarn: How to upgrade yarn version using terminal?

If you already have yarn 1.x and you want to upgrade to yarn 2. You need to do something a bit different:

yarn set version berry

Where berry is the code name for yarn version 2. See this migration guide here for more info.

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

Change the row color in DataGridView based on the quantity of a cell value

This might be helpful

  1. Use the "RowPostPaint" event
  2. The name of the column is NOT the "Header" of the column. You have to go to the properties for the DataGridView => then select the column => then look for the "Name" property

I converted this from C# ('From: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=74)

    Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) 
    Handles dgv_EmployeeTraining.RowPostPaint

    If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
        Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)

    '<== This is the header Name
        'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then  


    '<== But this is the name assigned to it in the properties of the control
        If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then   

            dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)

        Else
            dgvRow.DefaultCellStyle.BackColor = Color.LightPink

        End If

    End If

End Sub

Regular Expression to get all characters before "-"

So I see many possibilities to achieve this.

string text = "Foobar-test";
  1. Regex Match everything till the first "-"

    Match result = Regex.Match(text, @"^.*?(?=-)");
    
    • ^ match from the start of the string
    • .*? match any character (.), zero or more times (*) but as less as possible (?)
    • (?=-) till the next character is a "-" (this is a positive look ahead)
  2. Regex Match anything that is not a "-" from the start of the string

    Match result2 = Regex.Match(text, @"^[^-]*");
    
    • [^-]* matches any character that is not a "-" zero or more times
  3. Regex Match anything that is not a "-" from the start of the string till a "-"

    Match result21 = Regex.Match(text, @"^([^-]*)-");
    

    Will only match if there is a dash in the string, but the result is then found in capture group 1.

  4. Split on "-"

    string[] result3 = text.Split('-');
    

    Result is an Array the part before the first "-" is the first item in the Array

  5. Substring till the first "-"

    string result4 = text.Substring(0, text.IndexOf("-"));
    

    Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-"))

You get then all the results (all the same) with this

Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);

I would prefer the first method.

You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.

AngularJS: factory $http.get JSON file

I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.

By default IIS Express restricted access to local files (like json).

But, first: JSON have JavaScript syntax.

Second: javascript files is allowed.

So:

  1. rename JSON to JS (data.json->data.js).

  2. correct load command ($http.get('App/data.js').success(function (data) {...

  3. load script data.js to page (<script src="App/data.js"></script>)

Next use loaded data an usual manner. It is just workaround, of course.

Neatest way to remove linebreaks in Perl

Note from 2017: File::Slurp is not recommended due to design mistakes and unmaintained errors. Use File::Slurper or Path::Tiny instead.

extending on your answer

use File::Slurp ();
my $value = File::Slurp::slurp($filename);
$value =~ s/\R*//g;

File::Slurp abstracts away the File IO stuff and just returns a string for you.

NOTE

  1. Important to note the addition of /g , without it, given a multi-line string, it will only replace the first offending character.

  2. Also, the removal of $, which is redundant for this purpose, as we want to strip all line breaks, not just line-breaks before whatever is meant by $ on this OS.

  3. In a multi-line string, $ matches the end of the string and that would be problematic ).

  4. Point 3 means that point 2 is made with the assumption that you'd also want to use /m otherwise '$' would be basically meaningless for anything practical in a string with >1 lines, or, doing single line processing, an OS which actually understands $ and manages to find the \R* that proceed the $

Examples

while( my $line = <$foo> ){
      $line =~ $regex;
}

Given the above notation, an OS which does not understand whatever your files '\n' or '\r' delimiters, in the default scenario with the OS's default delimiter set for $/ will result in reading your whole file as one contiguous string ( unless your string has the $OS's delimiters in it, where it will delimit by that )

So in this case all of these regex are useless:

  • /\R*$// : Will only erase the last sequence of \R in the file
  • /\R*// : Will only erase the first sequence of \R in the file
  • /\012?\015?// : When will only erase the first 012\015 , \012 , or \015 sequence, \015\012 will result in either \012 or \015 being emitted.

  • /\R*$// : If there happens to be no byte sequences of '\015$OSDELIMITER' in the file, then then NO linebreaks will be removed except for the OS's own ones.

It would appear nobody gets what I'm talking about, so here is example code, that is tested to NOT remove line feeds. Run it, you'll see that it leaves the linefeeds in.

#!/usr/bin/perl 

use strict;
use warnings;

my $fn = 'TestFile.txt';

my $LF = "\012";
my $CR = "\015";

my $UnixNL = $LF;
my $DOSNL  = $CR . $LF;
my $MacNL  = $CR;

sub generate { 
    my $filename = shift;
    my $lineDelimiter = shift;

    open my $fh, '>', $filename;
    for ( 0 .. 10 )
    {
        print $fh "{0}";
        print $fh join "", map { chr( int( rand(26) + 60 ) ) } 0 .. 20;
        print $fh "{1}";
        print $fh $lineDelimiter->();
        print $fh "{2}";
    }
    close $fh;
}

sub parse { 
    my $filename = shift;
    my $osDelimiter = shift;
    my $message = shift;
    print "Parsing $message File $filename : \n";

    local $/ = $osDelimiter;

    open my $fh, '<', $filename;
    while ( my $line = <$fh> )
    {

        $line =~ s/\R*$//;
        print ">|" . $line . "|<";

    }
    print "Done.\n\n";
}


my @all = ( $DOSNL,$MacNL,$UnixNL);
generate 'Windows.txt' , sub { $DOSNL }; 
generate 'Mac.txt' , sub { $MacNL };
generate 'Unix.txt', sub { $UnixNL };
generate 'Mixed.txt', sub {
    return @all[ int(rand(2)) ];
};


for my $os ( ["$MacNL", "On Mac"], ["$DOSNL", "On Windows"], ["$UnixNL", "On Unix"]){
    for ( qw( Windows Mac Unix Mixed ) ){
        parse $_ . ".txt", @{ $os };
    }
}

For the CLEARLY Unprocessed output, see here: http://pastebin.com/f2c063d74

Note there are certain combinations that of course work, but they are likely the ones you yourself naívely tested.

Note that in this output, all results must be of the form >|$string|<>|$string|< with NO LINE FEEDS to be considered valid output.

and $string is of the general form {0}$data{1}$delimiter{2} where in all output sources, there should be either :

  1. Nothing between {1} and {2}
  2. only |<>| between {1} and {2}

How to list all tags along with the full message in git?

It's far from pretty, but you could create a script or an alias that does something like this:

for c in $(git for-each-ref refs/tags/ --format='%(refname)'); do echo $c; git show --quiet "$c"; echo; done

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

ImportError: No module named pip

In terminal try this:

ls -lA /usr/local/bin | grep pip

in my case i get:

-rwxr-xr-x 1 root  root      284 ??? 13 16:20 pip
-rwxr-xr-x 1 root  root      204 ??? 27 16:37 pip2
-rwxr-xr-x 1 root  root      204 ??? 27 16:37 pip2.7
-rwxr-xr-x 1 root  root      292 ??? 13 16:20 pip-3.4

So pip2 || pip2.7 in my case works, and pip

HTTP test server accepting GET/POST requests

https://httpbin.org/

It echoes the data used in your request for any of these types:

How To: Execute command line in C#, get STD OUT results

 System.Diagnostics.ProcessStartInfo psi =
   new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
 psi.RedirectStandardOutput = true;
 psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 psi.UseShellExecute = false;
 System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
 System.IO.StreamReader myOutput = proc.StandardOutput;
 proc.WaitForExit(2000);
 if (proc.HasExited)
  {
      string output = myOutput.ReadToEnd();
 }

No module named 'pymysql'

After trying a few things, and coming across PyMySQL Github, this worked:

sudo pip install PyMySQL

And to import use:

import pymysql

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

auto run a bat script in windows 7 at login

Just enable parsing of the autoexec.bat in the registry, using these instructions.

:: works only on windows vista and earlier 
Run REGEDT32.EXE.
Modify the following value within HKEY_CURRENT_USER: 

Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec 

1 = autoexec.bat is parsed
0 = autoexec.bat is not parsed

jquery drop down menu closing by clicking outside

Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.

$(document).on('click', function(event) {
  if (!$(event.target).closest('#menucontainer').length) {
    // Hide the menus.
  }
});

Here function is initiated when clicking on document, but it excludes triggering from #menucontainer. For details https://css-tricks.com/dangers-stopping-event-propagation/

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

You can include a legend template in the chart options:

//legendTemplate takes a template as a string, you can populate the template with values from your dataset 
var options = {
  legendTemplate : '<ul>'
                  +'<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<li>'
                    +'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
                  +'</li>'
                +'<% } %>'
              +'</ul>'
  }

  //don't forget to pass options in when creating new Chart
  var lineChart = new Chart(element).Line(data, options);

  //then you just need to generate the legend
  var legend = lineChart.generateLegend();

  //and append it to your page somewhere
  $('#chart').append(legend);

You'll also need to add some basic css to get it looking ok.

Check if element is clickable in Selenium Java

List<WebElement> wb=driver.findElements(By.xpath(newXpath));
        for(WebElement we: wb){
            if(we.isDisplayed() && we.isEnabled())
            {
                we.click();
                break;
            }
        }
    }

Regular Expression to get a string between parentheses in Javascript

_x000D_
_x000D_
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');_x000D_
console.log(str) // Inside brackets
_x000D_
_x000D_
_x000D_

How do I handle Database Connections with Dapper in .NET?

Try this:

public class ConnectionProvider
    {
        DbConnection conn;
        string connectionString;
        DbProviderFactory factory;

        // Constructor that retrieves the connectionString from the config file
        public ConnectionProvider()
        {
            this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString.ToString();
            factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[0].ProviderName.ToString());
        }

        // Constructor that accepts the connectionString and Database ProviderName i.e SQL or Oracle
        public ConnectionProvider(string connectionString, string connectionProviderName)
        {
            this.connectionString = connectionString;
            factory = DbProviderFactories.GetFactory(connectionProviderName);
        }

        // Only inherited classes can call this.
        public DbConnection GetOpenConnection()
        {
            conn = factory.CreateConnection();
            conn.ConnectionString = this.connectionString;
            conn.Open();

            return conn;
        }

    }

The remote server returned an error: (403) Forbidden

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

angularjs: ng-src equivalent for background-image:url(...)

ngSrc is a native directive, so it seems you want a similar directive that modifies your div's background-image style.

You could write your own directive that does exactly what you want. For example

app.directive('backImg', function(){
    return function(scope, element, attrs){
        var url = attrs.backImg;
        element.css({
            'background-image': 'url(' + url +')',
            'background-size' : 'cover'
        });
    };
});?

Which you would invoke like this

<div back-img="<some-image-url>" ></div>

JSFiddle with cute cats as a bonus: http://jsfiddle.net/jaimem/aSjwk/1/

accepting HTTPS connections with self-signed certificates

None of these fixes worked for my develop platform targeting SDK 16, Release 4.1.2, so I found a workaround.

My app stores data on server using "http://www.example.com/page.php?data=somedata"

Recently page.php was moved to "https://www.secure-example.com/page.php" and I keep getting "javax.net.ssl.SSLException: Not trusted server certificate".

Instead of accepting all certificates for only a single page, starting with this guide I solved my problem writing my own page.php published on "http://www.example.com/page.php"

<?php

caronte ("https://www.secure-example.com/page.php");

function caronte($url) {
    // build curl request
    $ch = curl_init();
    foreach ($_POST as $a => $b) {
        $post[htmlentities($a)]=htmlentities($b);
    }
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));

    // receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);

    echo $server_output;
}

?>

Way to run Excel macros from command line or batch file?

You can check if Excel is already open. There is no need to create another isntance

   If CheckAppOpen("excel.application")  Then
           'MsgBox "App Loaded"
            Set xlApp = GetObject(, "excel.Application")   
   Else
            ' MsgBox "App Not Loaded"
            Set  wrdApp = CreateObject(,"excel.Application")   
   End If

How can I open a website in my web browser using Python?

From the doc.

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.

To open in new tab:

import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)

Also from the doc.

If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible

So according to the value of new, you can either open page in same browser window or in new tab etc.

Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.

How to store a command in a variable in a shell script?

I tried various different methods:

printexec() {
  printf -- "\033[1;37m$\033[0m"
  printf -- " %q" "$@"
  printf -- "\n"
  eval -- "$@"
  eval -- "$*"
  "$@"
  "$*"
}

Output:

$ printexec echo  -e "foo\n" bar
$ echo -e foo\\n bar
foon bar
foon bar
foo
 bar
bash: echo -e foo\n bar: command not found

As you can see, only the third one, "$@" gave the correct result.

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

How can I change text color via keyboard shortcut in MS word 2010

You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.

How do I install boto?

  1. If necessary, install pip:

    sudo apt-get install python-pip

  2. Then install boto:

    pip install -U boto

How do I get only directories using Get-ChildItem?

From PowerShell v2 and newer (k represents the folder you are beginning your search at):

Get-ChildItem $Path -attributes D -Recurse

If you just want folder names only, and nothing else, use this:

Get-ChildItem $Path -Name -attributes D -Recurse

If you are looking for a specific folder, you could use the following. In this case, I am looking for a folder called myFolder:

Get-ChildItem $Path -attributes D -Recurse -include "myFolder"