Programs & Examples On #Nexusdb

NexusDB is an SQL database engine, embedded(free) and stand-alone(commercial).

Where does Chrome store extensions?

For my Mac, extensions were here:

~/Library/Application Support/Google/Chrome/Default/Extensions/

if you go to chrome://extensions you'll find the "ID" of each extension. That is going to be a directory within Extensions directory. It is there you'll find all of the extension's files.

How do I merge changes to a single file, rather than merging commits?

I found this approach simple and useful: How to "merge" specific files from another branch

As it turns out, we’re trying too hard. Our good friend git checkout is the right tool for the job.

git checkout source_branch <paths>...

We can simply give git checkout the name of the feature branch A and the paths to the specific files that we want to add to our master branch.

Please read the whole article for more understanding

React Error: Target Container is not a DOM Element

Also you can do something like that:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

"Application tried to present modally an active controller"?

Assume you have three view controllers instantiated like so:

UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];

You have added them to a tab bar like this:

UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];

Now you are trying to do something like this:

[tabBarController presentModalViewController:vc3];

This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.

Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".

In what cases do I use malloc and/or new?

There are a few things which new does that malloc doesn’t:

  1. new constructs the object by calling the constructor of that object
  2. new doesn’t require typecasting of allocated memory.
  3. It doesn’t require an amount of memory to be allocated, rather it requires a number of objects to be constructed.

So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

Multiline text in JLabel

You can do it by putting HTML in the code, so:

JFrame frame = new JFrame();
frame.setLayout(new GridLayout());
JLabel label = new JLabel("<html>First line<br>Second line</html>");
frame.add(label);
frame.pack();
frame.setVisible(true);

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

jackson deserialization json to java-objects

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

Best way to check if a URL is valid

Came across this article from 2012. It takes into account variables that may or may not be just plain URLs.

The author of the article, David Müeller, provides this function that he says, "...could be worth wile [sic]," along with some examples of filter_var and its shortcomings.

/**
 * Modified version of `filter_var`.
 *
 * @param  mixed $url Could be a URL or possibly much more.
 * @return bool
 */
function validate_url( $url ) {
    $url = trim( $url );

    return (
        ( strpos( $url, 'http://' ) === 0 || strpos( $url, 'https://' ) === 0 ) &&
        filter_var(
            $url,
            FILTER_VALIDATE_URL,
            FILTER_FLAG_SCHEME_REQUIRED || FILTER_FLAG_HOST_REQUIRED
        ) !== false
    );
}

Maven Out of Memory Build Failure

This happens in big projects on Windows when cygwin or other linux emulator is used(git bash). By some coincidence, both does not work on my project, what is an big open source project. In a sh script, a couple of mvn commands are called. The memory size grows to heap size bigger that specified in Xmx and most of the time in a case second windows process is started. This is making the memory consumption even higher.

The solution in this case is to use batch file and reduced Xmx size and then the maven operations are successful. If there is interest I can reveal more details.

ECONNREFUSED error when connecting to mongodb from node.js

sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

I thought I'd add that for Tomcat 7.x, <Context> is not in the server.xml, but in the context.xml. Removing and re-adding the project did not seem to help my similar issue, which was a web.xml issue, which I found out by checking the context.xml which had this line in the <Context> section:

<WatchedResource>WEB-INF/web.xml</WatchedResource>

The solution in WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property brought me closer to my answer, as the change of publishing into a separate XML did resolve the error reported above for me, but unfortunately it generated a second error that I'm still investigating.

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:myproject' did not find a matching property.

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

  • Open Terminal.
  • Go to Edit -> Profile Preferences.
  • Select the Title & command Tab in the window opened.
  • Mark the checkbox Run command as login shell.
  • close the window and restart the Terminal.

Check this Official Linkenter image description here

Making an svg image object clickable with onclick, avoiding absolute positioning

You could use following code:

<style>
    .svgwrapper {
        position: relative;
    }
    .svgwrapper {
        position: absolute;
        z-index: -1;
    }
</style>

<div class="svgwrapper" onClick="function();">
    <object src="blah" />
</div>

b3ng0 wrote similar code but it does not work. z-index of parent must be auto.

How do you switch pages in Xamarin.Forms?

By using the PushAsync() method you can push and PopModalAsync() you can pop pages to and from the navigation stack. In my code example below I have a Navigation page (Root Page) and from this page I push a content page that is a login page once I am complete with my login page I pop back to the root page

~~~ Navigation can be thought of as a last-in, first-out stack of Page objects.To move from one page to another an application will push a new page onto this stack. To return back to the previous page the application will pop the current page from the stack. This navigation in Xamarin.Forms is handled by the INavigation interface

Xamarin.Forms has a NavigationPage class that implements this interface and will manage the stack of Pages. The NavigationPage class will also add a navigation bar to the top of the screen that displays a title and will also have a platform appropriate Back button that will return to the previous page. The following code shows how to wrap a NavigationPage around the first page in an application:

Reference to content listed above and a link you should review for more information on Xamarin Forms, see the Navigation section:

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/introduction-to-xamarin-forms/

~~~

public class MainActivity : AndroidActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        Xamarin.Forms.Forms.Init(this, bundle);
        // Set our view from the "main" layout resource
        SetPage(BuildView());
    }

    static Page BuildView()
    {
        var mainNav = new NavigationPage(new RootPage());
        return mainNav;
    }
}


public class RootPage : ContentPage
{
    async void ShowLoginDialog()
    {
        var page = new LoginPage();

        await Navigation.PushModalAsync(page);
    }
}

//Removed code for simplicity only the pop is displayed

private async void AuthenticationResult(bool isValid)
{
    await navigation.PopModalAsync();
}

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

What does the 'static' keyword do in a class?

To add to existing answers, let me try with a picture:

An interest rate of 2% is applied to ALL savings accounts. Hence it is static.

A balance should be individual, so it is not static.

enter image description here

How can I remove specific rules from iptables?

First list all iptables rules with this command:

iptables -S

it lists like:

-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

Then copy the desired line, and just replace -A with -D to delete that:

iptables -D XYZ -p ...

editing PATH variable on mac

Based on my own experiences and internet search, I find these places work:

/etc/paths.d

~/.bash_profile

Note that you should open a new terminal window to see the changes.

You may also refer to this this question

TypeScript and field initializers

Update

Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.


Old answer

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    first: string;
    last: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        first: "Bob",
        last: "Smith",
    },
    age: 35,
};

Run MySQLDump without Locking Tables

Due to https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables :

Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list.

Order columns through Bootstrap4

2018 - Revisiting this question with the latest Bootstrap 4.

The responsive ordering classes are now order-first, order-last and order-0 - order-12

The Bootstrap 4 push pull classes are now push-{viewport}-{units} and pull-{viewport}-{units} and the xs- infix has been removed. To get the desired 1-3-2 layout on mobile/xs would be: Bootstrap 4 push pull demo (This only works pre 4.0 beta)


Bootstrap 4.1+

Since Bootstrap 4 is flexbox, it's easy to change the order of columns. The cols can be ordered from order-1 to order-12, responsively such as order-md-12 order-2 (last on md, 2nd on xs) relative to the parent .row.

<div class="container">
    <div class="row">
        <div class="col-3 col-md-6">
            <div class="card card-body">1</div>
        </div>
        <div class="col-6 col-md-12 order-2 order-md-12">
            <div class="card card-body">3</div>
        </div>
        <div class="col-3 col-md-6 order-3">
            <div class="card card-body">2</div>
        </div>
    </div>
</div>

Demo: Change order using order-* classes

Desktop (larger screens): enter image description here

Mobile (smaller screens): enter image description here

It's also possible to change column order using the flexbox direction utils...

<div class="container">
    <div class="row flex-column-reverse flex-md-row">
        <div class="col-md-8">
            2
        </div>
        <div class="col-md-4">
            1st on mobile
        </div>
    </div>
</div>

Demo: Bootstrap 4.1 Change Order with Flexbox Direction


Older version demos
demo - alpha 6
demo - beta (3)

See more Bootstrap 4.1+ ordering demos


Related:
Column ordering in Bootstrap 4 with push/pull and col-md-12
Bootstrap 4 change order of columns

A-C-B A-B-C

How to get selenium to wait for ajax response?

For those who is using primefaces, just do:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().$.active==0", defaultWaitingPeriod);

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

Can I get div's background-image url?

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});

Sanitizing strings to make them URL and filename safe?

Depending on how you will use it, you might want to add a length limit to protect against buffer overflows.

How do I get the find command to print out the file size with the file name?

find . -name '*.ear' -exec du -h {} \;

This gives you the filesize only, instead of all the unnecessary stuff.

Using ls to list directories and their total sizes

To list the largest directories from the current directory in human readable format:

du -sh * | sort -hr

A better way to restrict number of rows can be

du -sh * | sort -hr | head -n10

Where you can increase the suffix of -n flag to restrict the number of rows listed

Sample:

[~]$ du -sh * | sort -hr
48M app
11M lib
6.7M    Vendor
1.1M    composer.phar
488K    phpcs.phar
488K    phpcbf.phar
72K doc
16K nbproject
8.0K    composer.lock
4.0K    README.md

It makes it more convenient to read :)

Changing font size and direction of axes text in ggplot2

Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below

ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x  = element_blank())

I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.

how to hide keyboard after typing in EditText in android?

   mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // do something, e.g. set your TextView here via .setText()
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });

and in xml

  android:imeOptions="actionDone"

Can I install/update WordPress plugins without providing FTP access?

The best way to install plugin using SSH is WPCLI.

Note that, SSH access is mandatory to use WP CLI commands. Before using it check whether the WP CLI is installed at your hosting server or machine.

How to check : wp --version [ It will show the wp cli version installed ]

If not installed, how to install it : Before installing WP-CLI, please make sure the environment meets the minimum requirements:

UNIX-like environment (OS X, Linux, FreeBSD, Cygwin); limited support in Windows environment. PHP 5.4 or later WordPress 3.7 or later. Versions older than the latest WordPress release may have degraded functionality

If above points satisfied, please follow the steps : Reference URL : WPCLI

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
[ download the wpcli phar ]

php wp-cli.phar --info [ check whether the phar file is working ]

chmod +x wp-cli.phar [ change permission ]
sudo mv wp-cli.phar /usr/local/bin/wp [ move to global folder ]
wp --info [ to check the installation ]

Now WP CLI is ready to install.

Now you can install any plugin that is available in WordPress.org by using the following commands :

wp install plugin plugin-slug
wp delete plugin plugin-slug
wp deactivate plugin plugin-slug

NOTE : wp cli can install only those plugin which is available in wordpress.org

How to run docker-compose up -d at system start up?

Use restart: always in your docker compose file.

Docker-compose up -d will launch container from images again. Use docker-compose start to start the stopped containers, it never launches new containers from images.

nginx:   
    restart: always   
    image: nginx   
    ports:
      - "80:80"
      - "443:443"   links:
      - other_container:other_container

Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

As of JDK 8u102, the posted solutions relying on reflection will no longer work: the field that these solutions set is now final (https://bugs.openjdk.java.net/browse/JDK-8149417).

Looks like it's back to either (a) using Bouncy Castle, or (b) installing the JCE policy files.

Moment.js - How to convert date string into date?

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

How do you add a timed delay to a C++ program?

On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.

Detecting Windows or Linux?

Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0

public class OSValidator {

    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void main(String[] args) {

        System.out.println(OS);

        if (isWindows()) {
            System.out.println("This is Windows");
        } else if (isMac()) {
            System.out.println("This is Mac");
        } else if (isUnix()) {
            System.out.println("This is Unix or Linux");
        } else if (isSolaris()) {
            System.out.println("This is Solaris");
        } else {
            System.out.println("Your OS is not support!!");
        }
    }

    public static boolean isWindows() {
        return OS.contains("win");
    }

    public static boolean isMac() {
        return OS.contains("mac");
    }

    public static boolean isUnix() {
        return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
    }

    public static boolean isSolaris() {
        return OS.contains("sunos");
    }
    public static String getOS(){
        if (isWindows()) {
            return "win";
        } else if (isMac()) {
            return "osx";
        } else if (isUnix()) {
            return "uni";
        } else if (isSolaris()) {
            return "sol";
        } else {
            return "err";
        }
    }

}

How to create an installer for a .net Windows Service using Visual Studio

InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.

Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.

Augmenting InstallShield using Windows Installer XML - Windows Services

IsWiX Windows Service Tutorial

IsWiX Windows Service Video

Install psycopg2 on Ubuntu

Using Ubuntu 12.04 it appears to work fine for me:

jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  python-psycopg2-doc
The following NEW packages will be installed
  python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.

What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update to make sure your repo. is up to date.

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

AngularJS Multiple ng-app within a page

In my case I had to wrap the bootstrapping of my second app in angular.element(document).ready for it to work:

angular.element(document).ready(function() {
  angular.bootstrap(document.getElementById("app2"), ["app2"]);
});   

How can I cast int to enum?

From an int:

YourEnum foo = (YourEnum)yourInt;

From a string:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
}

Update:

From number you can also

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);

Execute and get the output of a shell command in node.js

This is the method I'm using in a project I am currently working on.

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

Example of retrieving a git user:

module.exports.getGitUser = function(callback){
    execute("git config --global user.name", function(name){
        execute("git config --global user.email", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
        });
    });
};

Creating a timer in python

mins = minutes + 1

should be

minutes = minutes + 1

Also,

minutes = 0

needs to be outside of the while loop.

How to get the return value from a thread in python?

Taking into consideration @iman comment on @JakeBiesinger answer I have recomposed it to have various number of threads:

from multiprocessing.pool import ThreadPool

def foo(bar, baz):
    print 'hello {0}'.format(bar)
    return 'foo' + baz

numOfThreads = 3 
results = []

pool = ThreadPool(numOfThreads)

for i in range(0, numOfThreads):
    results.append(pool.apply_async(foo, ('world', 'foo'))) # tuple of args for foo)

# do some other stuff in the main process
# ...
# ...

results = [r.get() for r in results]
print results

pool.close()
pool.join()

Cheers,

Guy.

How do I make a div full screen?

You can use HTML5 Fullscreen API for this (which is the most suitable way i think).

The fullscreen has to be triggered via a user event (click, keypress) otherwise it won't work.

Here is a button which makes the div fullscreen on click. And in fullscreen mode, the button click will exit fullscreen mode.

_x000D_
_x000D_
$('#toggle_fullscreen').on('click', function(){_x000D_
  // if already full screen; exit_x000D_
  // else go fullscreen_x000D_
  if (_x000D_
    document.fullscreenElement ||_x000D_
    document.webkitFullscreenElement ||_x000D_
    document.mozFullScreenElement ||_x000D_
    document.msFullscreenElement_x000D_
  ) {_x000D_
    if (document.exitFullscreen) {_x000D_
      document.exitFullscreen();_x000D_
    } else if (document.mozCancelFullScreen) {_x000D_
      document.mozCancelFullScreen();_x000D_
    } else if (document.webkitExitFullscreen) {_x000D_
      document.webkitExitFullscreen();_x000D_
    } else if (document.msExitFullscreen) {_x000D_
      document.msExitFullscreen();_x000D_
    }_x000D_
  } else {_x000D_
    element = $('#container').get(0);_x000D_
    if (element.requestFullscreen) {_x000D_
      element.requestFullscreen();_x000D_
    } else if (element.mozRequestFullScreen) {_x000D_
      element.mozRequestFullScreen();_x000D_
    } else if (element.webkitRequestFullscreen) {_x000D_
      element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);_x000D_
    } else if (element.msRequestFullscreen) {_x000D_
      element.msRequestFullscreen();_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
#container{_x000D_
  border:1px solid red;_x000D_
  border-radius: .5em;_x000D_
  padding:10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="container">_x000D_
  <p>_x000D_
    <a href="#" id="toggle_fullscreen">Toggle Fullscreen</a>_x000D_
  </p>_x000D_
  I will be fullscreen, yay!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please also note that Fullscreen API for Chrome does not work in non-secure pages. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

Another thing to note is the :fullscreen CSS selector. You can append this to any css selector so the that the rules will be applied when that element is fullscreen:

#container:-webkit-full-screen,
#container:-moz-full-screen,
#container:-ms-fullscreen,
#container:fullscreen {
    width: 100vw;
    height: 100vh;
    }

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

How to put a Scanner input into an array... for example a couple of numbers

public static void main (String[] args)
{
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter size of an array");
    int n=s.nextInt();
    double arr[] = new double[n];
    System.out.println("Please enter elements of array:");
    for (int i=0; i<n; i++)
    {
        arr[i] = s.nextDouble();
    }
}

nodejs module.js:340 error: cannot find module

Restart your command prompt and check your path variable (type: path). If you can't find find nodejs installation dir from output add it to the path variable and remember to restart cdm again...

Check if Key Exists in NameValueCollection

I am using this collection, when I worked in small elements collection.

Where elements lot, I think need use "Dictionary". My code:

NameValueCollection ProdIdes;
string prodId = _cfg.ProdIdes[key];
if (string.IsNullOrEmpty(prodId))
{
    ......
}

Or may be use this:

 string prodId = _cfg.ProdIdes[key] !=null ? "found" : "not found";

How to set time zone in codeigniter?

As describe here

  1. Open your php.ini file (look for it)

  2. Add the following line of code on the top of the file:

    date.timezone = "US/Central"

  3. Verify the changes by going to phpinfo.php

How to delete/truncate tables from Hadoop-Hive?

Use the following to delete all the tables in a linux environment.

hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'

jQuery select all except first

My answer is focused to a extended case derived from the one exposed at top.

Suppose you have group of elements from which you want to hide the child elements except first. As an example:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>
  1. We want to hide all .child elements on every group. So this will not help because will hide all .child elements except visible#1:

    $('.child:not(:first)').hide();
    
  2. The solution (in this extended case) will be:

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });
    

Simplest way to merge ES6 Maps/Sets?

For reasons I do not understand, you cannot directly add the contents of one Set to another with a built-in operation. Operations like union, intersect, merge, etc... are pretty basic set operations, but are not built-in. Fortunately, you can construct these all yourself fairly easily.

So, to implement a merge operation (merging the contents of one Set into another or one Map into another), you can do this with a single .forEach() line:

var s = new Set([1,2,3]);
var t = new Set([4,5,6]);

t.forEach(s.add, s);
console.log(s);   // 1,2,3,4,5,6

And, for a Map, you could do this:

var s = new Map([["key1", 1], ["key2", 2]]);
var t = new Map([["key3", 3], ["key4", 4]]);

t.forEach(function(value, key) {
    s.set(key, value);
});

Or, in ES6 syntax:

t.forEach((value, key) => s.set(key, value));

FYI, if you want a simple subclass of the built-in Set object that contains a .merge() method, you can use this:

// subclass of Set that adds new methods
// Except where otherwise noted, arguments to methods
//   can be a Set, anything derived from it or an Array
// Any method that returns a new Set returns whatever class the this object is
//   allowing SetEx to be subclassed and these methods will return that subclass
//   For this to work properly, subclasses must not change behavior of SetEx methods
//
// Note that if the contructor for SetEx is passed one or more iterables, 
// it will iterate them and add the individual elements of those iterables to the Set
// If you want a Set itself added to the Set, then use the .add() method
// which remains unchanged from the original Set object.  This way you have
// a choice about how you want to add things and can do it either way.

class SetEx extends Set {
    // create a new SetEx populated with the contents of one or more iterables
    constructor(...iterables) {
        super();
        this.merge(...iterables);
    }

    // merge the items from one or more iterables into this set
    merge(...iterables) {
        for (let iterable of iterables) {
            for (let item of iterable) {
                this.add(item);
            }
        }
        return this;        
    }

    // return new SetEx object that is union of all sets passed in with the current set
    union(...sets) {
        let newSet = new this.constructor(...sets);
        newSet.merge(this);
        return newSet;
    }

    // return a new SetEx that contains the items that are in both sets
    intersect(target) {
        let newSet = new this.constructor();
        for (let item of this) {
            if (target.has(item)) {
                newSet.add(item);
            }
        }
        return newSet;        
    }

    // return a new SetEx that contains the items that are in this set, but not in target
    // target must be a Set (or something that supports .has(item) such as a Map)
    diff(target) {
        let newSet = new this.constructor();
        for (let item of this) {
            if (!target.has(item)) {
                newSet.add(item);
            }
        }
        return newSet;        
    }

    // target can be either a Set or an Array
    // return boolean which indicates if target set contains exactly same elements as this
    // target elements are iterated and checked for this.has(item)
    sameItems(target) {
        let tsize;
        if ("size" in target) {
            tsize = target.size;
        } else if ("length" in target) {
            tsize = target.length;
        } else {
            throw new TypeError("target must be an iterable like a Set with .size or .length");
        }
        if (tsize !== this.size) {
            return false;
        }
        for (let item of target) {
            if (!this.has(item)) {
                return false;
            }
        }
        return true;
    }
}

module.exports = SetEx;

This is meant to be in it's own file setex.js that you can then require() into node.js and use in place of the built-in Set.

Replace a character at a specific index in a string?

this will work

   String myName="domanokz";
   String p=myName.replace(myName.charAt(4),'x');
   System.out.println(p);

Output : domaxokz

bootstrap multiselect get selected values

more efficient, due to less DOM lookups:

$('#multiselect1').multiselect({
    // ...
    onChange: function() {
        var selected = this.$select.val();
        // ...
    }
});

jQuery multiple conditions within if statement

A more general approach:

if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') )   {

       // Do something

}

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

If you don't want to run sudo then install ruby using homebrew

brew install ruby
export GEM_HOME="$HOME/.gem"
gem install rails

You may want to add export GEM_HOME="$HOME/.gem" to your ~/.bash_profile or .zshrc if you're using zsh

Note: RubyGems keeps old versions of gems, so feel free to do some cleaning after updating:

gem cleanup

Best timestamp format for CSV/Excel?

"yyyy-MM-dd hh:mm:ss.000" format does not work in all locales. For some (at least Danish) "yyyy-MM-dd hh:mm:ss,000" will work better.

How to dump raw RTSP stream to file?

With this command I had poor image quality

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4

With this, almost without delay, I got good image quality.

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

Why doesn't [01-12] range work as expected?

A character class in regular expressions, denoted by the [...] syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.

Your pattern, [01-12] is thus broken down as follows:

  • 0 - match the single digit 0
  • or, 1-1, match a single digit in the range of 1 through 1
  • or, 2, match a single digit 2

So basically all you're matching is 0, 1 or 2.

In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.

You have:

  • 01-09 (ie. first digit is 0, second digit is 1-9)
  • 10-12 (ie. first digit is 1, second digit is 0-2)

You will then have to write a regular expression for that, which can look like this:

  +-- a 0 followed by 1-9
  |
  |      +-- a 1 followed by 0-2
  |      |
<-+--> <-+-->
0[1-9]|1[0-2]
      ^
      |
      +-- vertical bar, this roughly means "OR" in this context

Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.

For instance, the pattern [0-1][0-9] would basically match the numbers 00-19, which is a bit more than what you want.

I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

PHP strtotime +1 month adding an extra month

today is 29th of January, +1 month means 29th of Fabruary, but because February consists of 28 days this year, it overlaps to the next day which is March 1st

instead try

strtotime('next month')

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

How do I make CMake output into a 'bin' dir?

$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

Sending email through Gmail SMTP server with C#

I had also try to many solution but make some changes it will work

host = smtp.gmail.com
port = 587
username = [email protected]
password = password
enabledssl = true

with smtpclient above parameters are work in gmail

RecyclerView: Inconsistency detected. Invalid item position

I am altering data for the RecyclerView in the background Thread. I got the same Exception as the OP. I added this after changing data:

myRecyclerView.post(new Runnable() {
    @Override
    public void run() {
        myRecyclerAdapter.notifyDataSetChanged();
    }
});

Hope it helps

Batch file to copy directories recursively

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

xcopy a: b: /s /e

What is the difference between function and procedure in PL/SQL?

  1. we can call a stored procedure inside stored Procedure,Function within function ,StoredProcedure within function but we can not call function within stored procedure.
  2. we can call function inside select statement.
  3. We can return value from function without passing output parameter as a parameter to the stored procedure.

This is what the difference i found. Please let me know if any .

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

What exactly is RESTful programming?

This is amazingly long "discussion" and yet quite confusing to say the least.

IMO:

1) There is no such a thing as restful programing, without a big joint and lots of beer :)

2) Representational State Transfer (REST) is an architectural style specified in the dissertation of Roy Fielding. It has a number of constraints. If your Service/Client respect those then it is RESTful. This is it.

You can summarize(significantly) the constraints to :

  • stateless communication
  • respect HTTP specs (if HTTP is used)
  • clearly communicates the content formats transmitted
  • use hypermedia as the engine of application state

There is another very good post which explains things nicely.

A lot of answers copy/pasted valid information mixing it and adding some confusion. People talk here about levels, about RESTFul URIs(there is not such a thing!), apply HTTP methods GET,POST,PUT ... REST is not about that or not only about that.

For example links - it is nice to have a beautifully looking API but at the end the client/server does not really care of the links you get/send it is the content that matters.

In the end any RESTful client should be able to consume to any RESTful service as long as the content format is known.

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Make sure JAVA_HOME is set and the path in environment variables reflects the bin directory of JAVA_HOME. Basically, the PATH should be able to find the keytools.exe file in your jdk location.

Use index in pandas to plot data

Try this,

monthly_mean.plot(y='A', use_index=True)

scp from Linux to Windows

I know this is old but I was struggling with the same. I haven't found a way to change directories, but if you just want to work with the C drive, scp defaults to C. To scp from Ubuntu to Windows, I ended up having to use (notice the double back-slashes):

scp /local/file/path [email protected]:Users\\Anshul\\Desktop

Hope this helps someone.

Why must wait() always be in synchronized block

What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

Let's illustrate what issues we would run into if wait() could be called outside of a synchronized block with a concrete example.

Suppose we were to implement a blocking queue (I know, there is already one in the API :)

A first attempt (without synchronization) could look something along the lines below

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();

    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }

    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}

This is what could potentially happen:

  1. A consumer thread calls take() and sees that the buffer.isEmpty().

  2. Before the consumer thread goes on to call wait(), a producer thread comes along and invokes a full give(), that is, buffer.add(data); notify();

  3. The consumer thread will now call wait() (and miss the notify() that was just called).

  4. If unlucky, the producer thread won't produce more give() as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.

Once you understand the issue, the solution is obvious: Use synchronized to make sure notify is never called between isEmpty and wait.

Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.


A paragraph from the link posted by @Willie summarizes it quite well:

You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.

The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty(). And the agreement is resolved by ensuring that the wait and notify are performed in synchronized blocks.


This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block

getResourceAsStream returns null

Lifepaths.class.getClass().getResourceAsStream(...) loads resources using system class loader, it obviously fails because it does not see your JARs

Lifepaths.class.getResourceAsStream(...) loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs

mysqli_real_connect(): (HY000/2002): No such file or directory

change localhost to 127.0.0.1 in /etc/phpmyadmin/config.inc.php

$cfg['Servers'][$i]['host'] = '127.0.0.1';

The reason for this is that pma tries to connect to the mysql.socket if you use localhost. If you use 127.0.0.1 PMA makes a TCP connection which should work.

How to get the filename without the extension in Java?

Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}

Find files in a folder using Java

What you want is File.listFiles(FileNameFilter filter).

That will give you a list of the files in the directory you want that match a certain filter.

The code will look similar to:

// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

MVC - Set selected value of SelectList

A bit late to the party here but here's how simple this is:

ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");

this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.

[edit] Here's how to use this in Razor:

@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })

Important: Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.

Hope this saves someone some time.

Test process.env with Jest

Depending on how you can organize your code, another option can be to put the environment variable within a function that's executed at runtime.

In this file, the environment variable is set at import time and requires dynamic requires in order to test different environment variables (as described in this answer):

const env = process.env.MY_ENV_VAR;

const envMessage = () => `MY_ENV_VAR is set to ${env}!`;

export default myModule;

In this file, the environment variable is set at envMessage execution time, and you should be able to mutate process.env directly in your tests:

const envMessage = () => {
  const env = process.env.MY_VAR;
  return `MY_ENV_VAR is set to ${env}!`;
}

export default myModule;

Jest test:

const vals = [
  'ONE',
  'TWO',
  'THREE',
];

vals.forEach((val) => {
  it(`Returns the correct string for each ${val} value`, () => {
    process.env.MY_VAR = val;

    expect(envMessage()).toEqual(...

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

If you are running in Android 29 then you have to use scoped storage or for now, you can bypass this issue by using:

android:requestLegacyExternalStorage="true"

in manifest in the application tag.

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

First, knowing where the data directory was for me was the key. /usr/local/var/mysql In here, there was at least one file with extension .err preceded with my local machine name. It had all info i needed to diagnose.

I think i screwed up by installing mysql 8 first. My app isn't compatible with it so i had to downgrade back to 5.7

My solution that worked for me was going to /usr/local/etc/my.cnf

Find this line if its there. I think its mysql 8 related:

mysqlx-bind-address = 127.0.0.1 

Remove it because in the mysql 5.7 says it doesnt like it in the error log

Also add this line in there if its not there under the bind-address.

socket=/tmp/mysql.sock

Go to the /tmp directory and delete any mysql.sock files in there. On server start, it will recreate the sock files

Trash out the data directory with mySQL in the stopped state. Mine was /usr/local/var/mysql . This is the same place where the logs are at

From there i ran

>mysqld --initialize

Then everything started working...this command will give you a random password at the end. Save that password for the next step

Running this to assign my own password.

>mysql_secure_installation 

Both

>brew services stop [email protected]

and

>mysql.server start

are now working. Hope this helps. It's about 3 hours of trial and error.

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

How to cd into a directory with space in the name?

$ DOCS="/cygdrive/c/Users/my\ dir/Documents"

Here's your first problem. This puts an actual backslash character into $DOCS, as you can see by running this command:

$ echo "$DOCS"
/cygdrive/c/Users/my\ `

When defining DOCS, you do need to escape the space character. You can quote the string (using either single or double quotes) or you can escape just the space character with a backslash. You can't do both. (On most Unix-like systems, you can have a backslash in a file or directory name, though it's not a good idea. On Cygwin or Windows, \ is a directory delimiter. But I'm going to assume the actual name of the directory is my dir, not my\ dir.)

$ cd $DOCS

This passes two arguments to cd. The first is cygdrive/c/Users/my\, and the second is dir/Documents. It happens that cd quietly ignores all but its first argument, which explains the error message:

-bash: cd: /cygdrive/c/Users/my\: No such file or directory

To set $DOCS to the name of your Documents directory, do any one of these:

$ DOCS="/cygdrive/c/Users/my dir/Documents"
$ DOCS='/cygdrive/c/Users/my dir/Documents'
$ DOCS=/cygdrive/c/Users/my\ dir/Documents

Once you've done that, to change to your Documents directory, enclose the variable reference in double quotes (that's a good idea for any variable reference in bash, unless you're sure the value doesn't have any funny characters):

$ cd "$DOCS"

You might also consider giving that directory a name without any spaces in it -- though that can be hard to do in general on Windows.

Python/BeautifulSoup - how to remove all tags from an element?

With BeautifulStoneSoup gone in bs4, it's even simpler in Python3

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
text = soup.get_text()
print(text)

Android - Center TextView Horizontally in LinearLayout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

convert string to specific datetime format?

  <%= string_to_datetime("2011-05-19 10:30:14") %>

  def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
    DateTime.strptime(string, format).to_time unless string.blank?
  end

Querying a linked sql server

You can use:

SELECT * FROM [aa-db-dev01].[TestDB].[dbo].[users];

Connect to network drive with user name and password

you can use system.diagnostocs.process to call out to 'net use .... with userid and password' or to a command shell that takes those.

Free easy way to draw graphs and charts in C++?

My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.

Code for best fit straight line of a scatter plot in python

Assuming line of best fit for a set of points is:

y = a + b * x
where:
b = ( sum(xi * yi) - n * xbar * ybar ) / sum((xi - xbar)^2)
a = ybar - b * xbar

Code and plot

# sample points 
X = [0, 5, 10, 15, 20]
Y = [0, 7, 10, 13, 20]

# solve for a and b
def best_fit(X, Y):

    xbar = sum(X)/len(X)
    ybar = sum(Y)/len(Y)
    n = len(X) # or len(Y)

    numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
    denum = sum([xi**2 for xi in X]) - n * xbar**2

    b = numer / denum
    a = ybar - b * xbar

    print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))

    return a, b

# solution
a, b = best_fit(X, Y)
#best fit line:
#y = 0.80 + 0.92x

# plot points and fit line
import matplotlib.pyplot as plt
plt.scatter(X, Y)
yfit = [a + b * xi for xi in X]
plt.plot(X, yfit)

enter image description here

UPDATE:

notebook version

Hadoop: «ERROR : JAVA_HOME is not set»

The solution that worked for me was setting my JAVA_HOME in /etc/environment

Though JAVA_HOME can be set inside the /etc/profile files, the preferred location for JAVA_HOME or any system variable is /etc/environment.

Open /etc/environment in any text editor like nano or vim and add the following line:

JAVA_HOME="/usr/lib/jvm/your_java_directory"

Load the variables:

source /etc/environment

Check if the variable loaded correctly:

echo $JAVA_HOME

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Actually you can use both - you can develop an app with amazon servers ec2. Then push it (with git) to heroku for free for awhile (use heroku free tier to serve it to the public) and test it like so. It is very cost effective in comparison to rent a server, but you will have to talk with a more restrictive heroku api which is something you should think about. Source: this method was adopted for one of my online classes "Startup engineering from Coursera/Stanford by Balaji S. Srinivasan and Vijay S. Pande

Added a scheme so my explanation will be easier to understand

C++ convert hex string to signed integer

Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.

char hextob(char ch)
{
    if (ch >= '0' && ch <= '9') return ch - '0';
    if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
    return 0;
}
template<typename T>
T hextot(char* hex)
{
    T value = 0;
    for (size_t i = 0; i < sizeof(T)*2; ++i)
        value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
    return value;
};

Usage:

int main()
{
    char str[4] = {'f','f','f','f'};
    std::cout << hextot<int16_t>(str)  << "\n";
}

Note: the length of the string must be divisible by 2

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

inject bean reference into a Quartz job in Spring?

Same problem has been resolved in LINK:

I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyy name="triggers">
    <list>
        <ref bean="simpleTrigger"/>
            </list>
    </property>
    <property name="applicationContextSchedulerContextKey">
        <value>applicationContext</value>
</property>

Then using below code in your job class you can get the applicationContext and get whatever bean you want.

appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");

Hope it helps. You can get more information from Mark Mclaren'sBlog

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

Git push error pre-receive hook declined

You might not have developer access to the project or master branch. You need dev access to push new work up.

New work meaning new branches and commits.

Creating and appending text to txt file in VB.NET

You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.

You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.

Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
   If (Not File.Exists(strFile)) Then
      sw = File.CreateText(strFile)
      sw.WriteLine("Start Error Log for today")
   Else
      sw = File.AppendText(strFile)
   End If
   sw.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
   sw.Close()
Catch ex As IOException
   MsgBox("Error writing to log file.")
End Try

Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

Strings as Primary Keys in SQL Database

Two reasons to use integers for PK columns:

  1. We can set identity for integer field which incremented automatically.

  2. When we create PKs, the db creates an index (Cluster or Non Cluster) which sorts the data before it's stored in the table. By using an identity on a PK, the optimizer need not check the sort order before saving a record. This improves performance on big tables.

What is console.log?

Apart from the usages mentioned above, console.log can also print to the terminal in node.js. A server created with express (for eg.) can use console.log to write to the output logger file.

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

CSS background image to fit height, width should auto-scale in proportion

I know this is an old answer but for others searching for this; in your CSS try:

background-size: auto 100%;

How to do a SOAP wsdl web services call from the command line

For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.

$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
    'Content-Type' = 'text/xml';
    'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
        <Body>
            <yourEnvelopeContentsHere/>
        </Body>
    </Envelope>
'@     # <--- This line must not be indented

Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope

How to call python script on excel vba?

To those who are stuck wondering why a window flashes and goes away without doing anything, the problem may related to the RELATIVE path in your Python script. e.g. you used ".\". Even the Python script and Excel Workbook is in the same directory, the Current Directory may still be different. If you don't want to modify your code to change it to an absolute path. Just change your current Excel directory before you run the python script by:

ChDir ActiveWorkbook.Path

I'm just giving a example here. If the flash do appear, one of the first issues to check is the Current Working Directory.

WordPress query single post by slug

As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:

function get_post_id_by_slug( $slug, $post_type = "post" ) {
    $query = new WP_Query(
        array(
            'name'   => $slug,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields'      => 'ids',
        ) );
    $posts = $query->get_posts();
    return array_shift( $posts );
}

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How merge two objects array in angularjs?

You can use angular.extend(dest, src1, src2,...);

In your case it would be :

angular.extend($scope.actions.data, data);

See documentation here :

https://docs.angularjs.org/api/ng/function/angular.extend

Otherwise, if you only get new values from the server, you can do the following

for (var i=0; i<data.length; i++){
    $scope.actions.data.push(data[i]);
}

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

Image overlay on responsive sized images bootstrap

Add a class to the containing div, then set the following css on it:

.img-overlay {
    position: relative;
    max-width: 500px; //whatever your max-width should be 
}

position: relative is required on a parent element of children with position: absolute for the children to be positioned in relation to that parent.

DEMO

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

Java: how do I initialize an array size if it's unknown?

I think you need use List or classes based on that.

For instance,

ArrayList<Integer> integers = new ArrayList<Integer>();
int j;

do{
    integers.add(int.nextInt());
    j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );

You could read this article for getting more information about how to use that.

Python string prints as [u'String']

You probably have a list containing one unicode string. The repr of this is [u'String'].

You can convert this to a list of byte strings using any variation of the following:

# Functional style.
print map(lambda x: x.encode('ascii'), my_list)

# List comprehension.
print [x.encode('ascii') for x in my_list]

# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode('ascii') for x in my_list)

# What do I care about the brackets anyway?
print ', '.join(repr(x.encode('ascii')) for x in my_list)

# That's actually not a good way of doing it.
print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list)

PHP String to Float

$rootbeer = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

Disable browser cache for entire ASP.NET website

HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

All requests get routed through default.aspx first - so assuming you can just pop in code behind there.

Why does an onclick property set with setAttribute fail to work in IE?

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

thanks to this post.

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}

Getting Date or Time only from a DateTime Object

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

Parsing HTTP Response in Python

I guess things have changed in python 3.4. This worked for me:

print("resp:" + json.dumps(resp.json()))

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

How can I add a hint or tooltip to a label in C# Winforms?

You have to add a ToolTip control to your form first. Then you can set the text it should display for other controls.

Here's a screenshot showing the designer after adding a ToolTip control which is named toolTip1:

enter image description here

Convert Select Columns in Pandas Dataframe to Numpy Array

The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence

You can also use '.array'.Refrence

Pandas .as_matrix deprecated since version 0.23.0.

How to completely uninstall Visual Studio 2010?

The only real clean way to uninstall VS (Visual Studio, whatever version it is) is to completely reinstall the whole OS. If you don't, more compatibility problems might surface.

Permanent solution

Starting from scratch (clean install, VS never installed on the OS), the best way to avoid all those problems is to install and run VS from a VM (virtual machine) as stated by Default in the comments above. This way, and as long as Microsoft doesn't do anything to improve its whole platform to be more user-friendly, switching from a version to another will be quick and easy and the main partition of the HDD (or SSD in my case) won't be filed with all the garbage that VS leaves behind.

Of course, the disadvantage is speed. The program will be slower in pretty much every way. But honestly, who uses VS for its speed? Even on the latest enthusiast-platforms, it takes ages to install. Even if VS might start up faster on a high-end SSD, it's just slow.

"The public type <<classname>> must be defined in its own file" error in Eclipse

If .java file contains top level (not nested) public class, it have same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file.

If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run).

So assuming your code is placed in StaticDemoShow.java file you have two options:

  1. If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)

    class StaticDemo { // It can no longer public
    
        static int a = 3;
        static int b = 4;
    
        static {
            System.out.println("Voila! Static block put into action");
        }
    
        static void show() {
            System.out.println("a= " + a);
            System.out.println("b= " + b);
        }
    
    }
    
    public class StaticDemoShow { // Only one top level public class in same .java file
        public static void main() {
            StaticDemo.show();
        }
    }
    
  2. Move all public classes to their own .java files. So in your case you would need to split it into two files:

    • StaticDemo.java

      public class StaticDemo { // Note: same name as name of file
      
          static int a = 3;
          static int b = 4;
      
          static {
              System.out.println("Voila! Static block put into action");
          }
      
          static void show() {
              System.out.println("a= " + a);
              System.out.println("b= " + b);
          }
      
      }
      
    • StaticDemoShow.java

      public class StaticDemoShow { 
          public static void main() {
              StaticDemo.show();
          }
      }
      

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

Python 3: EOF when reading a line (Sublime Text 2 is angry)

It seems as of now, the only solution is still to install SublimeREPL.

To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:

To enable it, go to Preferences->Key Bindings - User, and copy this in there:

[
    {"keys":["ctrl+r"] , 
    "caption": "SublimeREPL: Python - RUN current file",
    "command": "run_existing_window_command", 
    "args":
        {
            "id": "repl_python_run",
            "file": "config/Python/Main.sublime-menu"
        }
    },
]

Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.

How to create a static library with g++?

Create a .o file:

g++ -c header.cpp

add this file to a library, creating library if necessary:

ar rvs header.a header.o

use library:

g++ main.cpp header.a

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}

function declaration isn't a prototype

In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.

If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.

I suggest removing the extern, it is extraneous and is usually omitted.

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

How to read lines of a file in Ruby

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

Insert image after each list item

For IE8 support, the "content" property cannot be empty.

To get around this I've done the following :

.ul li:after {
    content:"icon";
    text-indent:-999em;
    display:block;
    width:32px;
    height:32px;
    background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
    margin:5% 0 0 45%;
}

Note : This works with image sprites too

How to use count and group by at the same select statement

You can use DISTINCT inside the COUNT like what milkovsky said

in my case:

select COUNT(distinct user_id) from answers_votes where answer_id in (694,695);

This will pull the count of answer votes considered the same user_id as one count

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

Gradle failed to resolve library in Android Studio

I had the same problem, the first thing that came to mind was repositories. So I checked the build.gradle file for the whole project and added the following code, then synchronized the gradle with project and problem was solved!

allprojects {
    repositories {
        jcenter()
    }
}

Search in lists of lists by given index

What about:

list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'b'

filter(lambda x:x[1]==search,list)

This will return each list in the list of lists with the second element being equal to search.

Java math function to convert positive int to negative and negative to positive?

Necromancing here.
Obviously, x *= -1; is far too simple.

Instead, we could use a trivial binary complement:

number = ~(number - 1) ;

Like this:

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int iPositive = 15;
        int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
        System.out.println(iNegative);

        iPositive =  ~(iNegative - 1)  ;
        System.out.println(iPositive);

        iNegative = 0;
        iPositive = ~(iNegative - 1);
        System.out.println(iPositive);


    }
}

That way we can ensure that mediocre programmers don't understand what's going on ;)

Simple PowerShell LastWriteTime compare

(ls $source).LastWriteTime

("ls", "dir", or "gci" are the default aliases for Get-ChildItem.)

What is the advantage of using heredoc in PHP?

Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

A very common example: echoing out HTML from within PHP:

$html = <<<HTML
  <div class='something'>
    <ul class='mylist'>
      <li>$something</li>
      <li>$whatever</li>
      <li>$testing123</li>
    </ul>
  </div>
HTML;

// Sometime later
echo $html;

It is easy to read and easy to maintain.

The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.

Updated answer for Your Common Sense

Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:

$sql = <<<SQL
       SELECT * FROM table
SQL;

Select subset of columns in data.table R

If it's not mandatory to specify column names:

> cor(dt[, !c(1:3, 5)])
             V4          V6          V7         V8          V9         V10
V4   1.00000000 -0.50472635 -0.07123705  0.9089868 -0.17232607 -0.77988709
V6  -0.50472635  1.00000000  0.05757776 -0.2374420  0.67334474  0.29476983
V7  -0.07123705  0.05757776  1.00000000 -0.1812176 -0.36093750  0.01102428
V8   0.90898683 -0.23744196 -0.18121755  1.0000000  0.21372140 -0.75798418
V9  -0.17232607  0.67334474 -0.36093750  0.2137214  1.00000000 -0.01179544
V10 -0.77988709  0.29476983  0.01102428 -0.7579842 -0.01179544  1.00000000

JavaScript Chart Library

In case what you need is bar chart only. I published some code I've been using in an old project. Someone told me the VML implementation is broken on recent versions of IE, but the SVG should work just fine. Might be getting back to the project and release some serverside renderers I already have and maybe WebGL rendering layer. There's a link: http://blog.conquex.com/?p=64

Pass values of checkBox to controller action in asp.net mvc4

 public ActionResult Save(Director director)
        {
          // IsActive my model property same name give in cshtml
//IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive" 
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

Can't get Gulp to run: cannot find module 'gulp-util'

This will solve all gulp problem

sudo npm install gulp && sudo npm install --save del && sudo gulp build

Using sed to split a string with a delimiter

To split a string with a delimiter with GNU sed you say:

sed 's/delimiter/\n/g'     # GNU sed

For example, to split using : as a delimiter:

$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you

Or with a non-GNU sed:

$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you

In this particular case, you missed the g after the substitution. Hence, it is just done once. See:

$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5

g stands for global and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.

All together, in your case you would need to use:

sed 's/:/\\n/g' ~/Desktop/myfile.txt

Note that you can directly use the sed ... file syntax, instead of unnecessary piping: cat file | sed.

ES6 exporting/importing in index file

You can easily re-export the default import:

export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';

There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

Reloading module giving NameError: name 'reload' is not defined

For python2 and python3 compatibility, you can use:

# Python 2 and 3
from imp import reload
reload(mymodule)

How to pass parameter to click event in Jquery

You don't need to pass the parameter, you can get it using .attr() method

$(function(){
    $('elements-to-match').click(function(){
        alert("The id is "+ $(this).attr("id") );
    });
});

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

final keyword in method parameters

Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.

Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

Either of the first two would be acceptable to me. I would avoid the last one because it is relatively easy to introduce a bug by putting a space between the quotes. This particular bug would be difficult to find by observation. Assuming no typos, all are semantically equivalent.

[EDIT]

Also, you might want to always use either string or String for consistency, but that's just me.

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

Replace whitespace with a comma in a text file in Linux

Try something like:

sed 's/[:space:]+/,/g' orig.txt > modified.txt

The character class [:space:] will match all whitespace (spaces, tabs, etc.). If you just want to replace a single character, eg. just space, use that only.

EDIT: Actually [:space:] includes carriage return, so this may not do what you want. The following will replace tabs and spaces.

sed 's/[:blank:]+/,/g' orig.txt > modified.txt

as will

sed 's/[\t ]+/,/g' orig.txt > modified.txt

In all of this, you need to be careful that the items in your file that are separated by whitespace don't contain their own whitespace that you want to keep, eg. two words.

How do I trim whitespace?

If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.

EXAMPLE:

txt="potatoes"
print("I love ",txt,"",sep="")

This will print: I love potatoes.

Instead of: I love potatoes .

In your case, since you would be trying to get ride of the \t, do sep="\t"

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I had a similar issue running unit tests using MSTEST under Jenkins. The fix in my case was to remove "Version=6.0.0.0, " as shown below:

Old:
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxx" requirePermission="false" />

New:
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Culture=neutral, PublicKeyToken=xxxx" requirePermission="false" />

I had to make this change is several App.config and Web.config files in my multi-project solution.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

adding text to an existing text element in javascript via DOM

What about this.

_x000D_
_x000D_
var p = document.getElementById("p")_x000D_
p.innerText = p.innerText+" And this is addon."
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

In STL maps, is it better to use map::insert than []?

This is a rather restricted case, but judging from the comments I've received I think it's worth noting.

I've seen people in the past use maps in the form of

map< const key, const val> Map;

to evade cases of accidental value overwriting, but then go ahead writing in some other bits of code:

const_cast< T >Map[]=val;

Their reason for doing this as I recall was because they were sure that in these certain bits of code they were not going to be overwriting map values; hence, going ahead with the more 'readable' method [].

I've never actually had any direct trouble from the code that was written by these people, but I strongly feel up until today that risks - however small - should not be taken when they can be easily avoided.

In cases where you're dealing with map values that absolutely must not be overwritten, use insert. Don't make exceptions merely for readability.

How to add spacing between columns?

it's simple .. you have to add solid border right, left to col-* and it should be work ..:)

it looks like this : http://i.stack.imgur.com/CF5ZV.png

HTML :

<div class="row">
     <div class="col-sm-3" id="services_block">

     </div>
     <div class="col-sm-3" id="services_block">

     </div>
     <div class="col-sm-3" id="services_block">

     </div>
     <div class="col-sm-3" id="services_block">

     </div>
</div>

CSS :

div#services_block {
   height: 355px;
   background-color: #33363a;
   border-left:3px solid white;
   border-right:3px solid white;
}

Enable UTF-8 encoding for JavaScript

I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:

    <parent>        
    <artifactId>eric-project-parent</artifactId>
    <groupId>com.eric.common</groupId>
     <!-- Should be 3.1.0.0-RELEASE -->
    <version>2.0.0.0-SNAPSHOT</version>     
    <relativePath>
                ../../EricParentAsset/projects/eric-project-parent</relativePath>           
</parent>

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Find largest and smallest number in an array

big=small=values[0]; //assigns element to be highest or lowest value

Should be AFTER fill loop

//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
    cout << "Enter value " << i << ": ";
    cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value

since when you declare array - it's unintialized (store some undefined values) and so, your big and small after assigning would store undefined values too.

And of course, you can use std::min_element, std::max_element, or std::minmax_element from C++11, instead of writing your loops.

Pass arguments into C program from command line

You could use getopt.

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

Add default value of datetime field in SQL Server to a timestamp

In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP. The datatype of that column may be datetime or datetime2.

e.g.

Create Table Student
(
  Name varchar(50),
  DateOfAddmission datetime default CURRENT_TIMESTAMP
);

How to restart Postgresql

macOS:

  1. On the top left of the MacOS menu bar you have the Postgres Icon
  2. Click on it this opens a drop down menu
  3. Click on Stop -> than click on start

How to remove certain characters from a string in C++?

For those of you that prefer a more concise, easier to read lambda coding style...

This example removes all non-alphanumeric and white space characters from a wide string. You can mix it up with any of the other ctype.h helper functions to remove complex-looking character-based tests.

(I'm not sure how these functions would handle CJK languages, so walk softly there.)

    // Boring C loops: 'for(int i=0;i<str.size();i++)' 
    // Boring C++ eqivalent: 'for(iterator iter=c.begin; iter != c.end; ++iter)'

See if you don't find this easier to understand than noisy C/C++ for/iterator loops:

TSTRING label = _T("1.   Replen & Move  RPMV");
TSTRING newLabel = label;
set<TCHAR> badChars; // Use ispunct, isalpha, isdigit, et.al. (lambda version, with capture list parameter(s) example; handiest thing since sliced bread)
for_each(label.begin(), label.end(), [&badChars](TCHAR n){
    if (!isalpha(n) && !isdigit(n))
        badChars.insert(n);
});

for_each(badChars.begin(), badChars.end(), [&newLabel](TCHAR n){
    newLabel.erase(std::remove(newLabel.begin(), newLabel.end(), n), newLabel.end());
});

newLabel results after running this code: "1ReplenMoveRPMV"

This is just academic, since it would clearly be more precise, concise and efficient to combine the 'if' logic from lambda0 (first for_each) into the single lambda1 (second for_each), if you have already established which characters are the "badChars".

Auto-indent spaces with C in vim?

and always remember this venerable explanation of Spaces + Tabs:

http://www.jwz.org/doc/tabs-vs-spaces.html

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.

Which header file do you include to use bool type in c in linux?

Try this header file in your code

stdbool.h

This must work