Programs & Examples On #Ansi escape

What are carriage return, linefeed, and form feed?

\f is used for page break. You cannot see any effect in the console. But when you use this character constant in your file then you can see the difference.

Other example is that if you can redirect your output to a file then you don't have to write a file or use file handling.

For ex:

Write this code in c++

void main()    
{
    clrscr();
    cout<<"helloooooo" ;

    cout<<"\f";
    cout<<"hiiiii" ;

}

and when you compile this it generate an exe(for ex. abc.exe)

then you can redirect your output to a file using this:

abc > xyz.doc

then open the file xyz.doc you can see the actual page break between hellooo and hiiii....

How to Query Database Name in Oracle SQL Developer?

DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.

Undefined symbols for architecture armv7

Here's how I got this problem:

I added a .h, .m and NIB from another project by dragging them onto my project navigator. Xcode didn't add them to the Build Phases properly.

Check my answer because I had a similar problem that I was able to solve by doing some steps.

Convert pyQt UI to python

For pyqt5 you can use

pyuic5 xyz.ui > xyz.py 

or

pyuic5 xyz.ui -o xyz.py

Is it better to use NOT or <> when comparing values?

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

Is there a MySQL option/feature to track history of changes to records?

MariaDB supports System Versioning since 10.3 which is the standard SQL feature that does exactly what you want: it stores history of table records and provides access to it via SELECT queries. MariaDB is an open-development fork of MySQL. You can find more on its System Versioning via this link:

https://mariadb.com/kb/en/library/system-versioned-tables/

How to return an array from an AJAX call?

Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.

Is there a short contains function for lists?

The list method index will return -1 if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if statement you can do the following:

if myItem in list:
    #do things

You can also check if an element is not in a list with the following if statement:

if myItem not in list:
    #do things

How to write a multiline command?

After trying almost every key on my keyboard:

C:\Users\Tim>cd ^
Mehr? Desktop

C:\Users\Tim\Desktop>

So it seems to be the ^ key.

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Select distinct rows from datatable in Linq

Check this link

get distinct rows from datatable using Linq (distinct with mulitiple columns)

Or try this

var distinctRows = (from DataRow dRow in dTable.Rows
                    select new  {  col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

EDIT: Placed the missing first curly brace.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

There is no such tool till now to print the heap memory in the format as you requested The Only and only way to print is to write a java program with the help of Runtime Class,

public class TestMemory {

public static void main(String [] args) {

    int MB = 1024*1024;

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    //Print used memory
    System.out.println("Used Memory:" 
        + (runtime.totalMemory() - runtime.freeMemory()) / MB);

    //Print free memory
    System.out.println("Free Memory:" 
        + runtime.freeMemory() / mb);

    //Print total available memory
    System.out.println("Total Memory:" + runtime.totalMemory() / MB);

    //Print Maximum available memory
    System.out.println("Max Memory:" + runtime.maxMemory() / MB);
}

}

reference:https://viralpatel.net/blogs/getting-jvm-heap-size-used-memory-total-memory-using-java-runtime/

Initializing IEnumerable<string> In C#

You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.

How to encode the filename parameter of Content-Disposition header in HTTP?

The following document linked from the draft RFC mentioned by Jim in his answer further addresses the question and definitely worth a direct note here:

Test Cases for HTTP Content-Disposition header and RFC 2231/2047 Encoding

UICollectionView auto scroll to cell at IndexPath

Swift:

your_CollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)

Swift 3

let indexPath = IndexPath(row: itemIndex, section: sectionIndex)

collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.right, animated: true)

Scroll Position:

UICollectionViewScrollPosition.CenteredHorizontally / UICollectionViewScrollPosition.CenteredVertically

How to revert the last migration?

Here is my solution, since the above solution do not really cover the use-case, when you use RunPython.

You can access the table via the ORM with

from django.db.migrations.recorder import MigrationRecorder

>>> MigrationRecorder.Migration.objects.all()
>>> MigrationRecorder.Migration.objects.latest('id')
Out[5]: <Migration: Migration 0050_auto_20170603_1814 for model>
>>> MigrationRecorder.Migration.objects.latest('id').delete()
Out[4]: (1, {u'migrations.Migration': 1})

So you can query the tables and delete those entries that are relevant for you. This way you can modify in detail. With RynPython migrations you also need to take care of the data that was added/changed/removed. The above example only displays, how you access the table via Djang ORM.

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

Attempted to read or write protected memory

Hi There are two possible reasons.

  1. We have un-managed code and we are calling it from managed code. that is preventing to run this code. try running these commands and restart your pc

    cmd: netsh winsock reset

open cmd.exe and run command "netsh winsock reset catalog"

  1. Anti-virus is considering un-managed code as harmful and restricting to run this code disable anti-virus and then check

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

Using "-Filter" with a variable

Or

-like '*'+$nameregex+'*'

if you would like to use wildcards.

How to stretch the background image to fill a div

Modern CSS3 (recommended for the future & probably the best solution)

.selector{
   background-size: cover;
   /* stretches background WITHOUT deformation so it would fill the background space,
      it may crop the image if the image's dimensions are in different ratio,
      than the element dimensions. */
}

Max. stretch without crop nor deformation (may not fill the background): background-size: contain;
Force absolute stretch (may cause deformation, but no crop): background-size: 100% 100%;

"Old" CSS "always working" way

Absolute positioning image as a first child of the (relative positioned) parent and stretching it to the parent size.

HTML

<div class="selector">
   <img src="path.extension" alt="alt text">
   <!-- some other content -->
</div>

Equivalent of CSS3 background-size: cover; :

To achieve this dynamically, you would have to use the opposite of contain method alternative (see below) and if you need to center the cropped image, you would need a JavaScript to do that dynamically - e.g. using jQuery:

$('.selector img').each(function(){ 
   $(this).css({ 
      "left": "50%", 
      "margin-left": "-"+( $(this).width()/2 )+"px", 
      "top": "50%", 
      "margin-top": "-"+( $(this).height()/2 )+"px" 
   }); 
});

Practical example:
css crop like example

Equivalent of CSS3 background-size: contain; :

This one can be a bit tricky - the dimension of your background that would overflow the parent will have CSS set to 100% the other one to auto. Practical example: css stretching background as image

.selector img{
   position: absolute; top:0; left: 0;
   width: 100%;
   height: auto;
   /* -- OR -- */
   /* width: auto; 
      height: 100%; */
}

Equivalent of CSS3 background-size: 100% 100%; :

.selector img{
   position: absolute; top:0; left: 0;
   width: 100%;
   height: 100%;
}

PS: To do the equivalents of cover/contain in the "old" way completely dynamically (so you will not have to care about overflows/ratios) you would have to use javascript to detect the ratios for you and set the dimensions as described...

How do you clear a stringstream variable?

my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

Sorting dropdown alphabetically in AngularJS

For anyone who wants to sort the variable in third layer:

<select ng-option="friend.pet.name for friend in friends"></select>

you can do it like this

<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>

Macro to Auto Fill Down to last adjacent cell

This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.

Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

How to run iPhone emulator WITHOUT starting Xcode?

As the multitude of answers indicate, there are lots of different ways to address this issue. Not all of them address what is my number one issue, and what seems to be the asker's priority, as well: The ability to launch from Spotlight.

Here's the solution that works well for me, and should work with any OS X and XCode versions. I've tested it on OS X 10.11 and XCode 7.3.

Initial setup does require launching XCode, but after that, you won't need to just to get to the Simulator.

Setup

  1. Launch XCode
  2. From the XCode menu, select Open Developer Tool > Simulator
  3. In the dock, control (or right) click on the Simulator icon
  4. Select Options > Show in Finder
  5. While holding down Command and Option, drag the Simulator icon to the applications directory. This creates an alias to it.
  6. If desired, rename the alias from "Simulator" to "iOS Simulator". Whatever you name it is what it will show up as in Spotlight.

Note: There are other ways to get to the location of the Simulator app (steps 1-4), such as using Go to Folder… in the Finder, but those require knowing the location of the Simulator to begin with. Since that has changed from version to version of XCode, this way should work regardless of these changes.

Use

  1. Launch Spotlight (command-space, etc.)
  2. Type "simulator" or "ios" (if you renamed the alias).
  3. If necessary, use the down arrow to scroll to the Simulator alias. Eventually, spotlight should learn and make the alias the top choice so you can skip this step.
  4. Hit return

Perl: function to trim string leading and trailing whitespace

I also use a positive lookahead to trim repeating spaces inside the text:

s/^\s+|\s(?=\s)|\s+$//g

Getting absolute URLs using ASP.NET Core

This is a variation of the anwser by Muhammad Rehan Saeed, with the class getting parasitically attached to the existing .net core MVC class of the same name, so that everything just works.

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// <see cref="IUrlHelper"/> extension methods.
    /// </summary>
    public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
        /// route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="actionName">The name of the action method.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteAction(
            this IUrlHelper url,
            string actionName,
            string controllerName,
            object routeValues = null)
        {
            return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
        /// virtual (relative) path to an application absolute path.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="contentPath">The content path.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteContent(
            this IUrlHelper url,
            string contentPath)
        {
            HttpRequest request = url.ActionContext.HttpContext.Request;
            return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified route by using the route name and route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteRouteUrl(
            this IUrlHelper url,
            string routeName,
            object routeValues = null)
        {
            return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }
    }
}

Arrays.asList() of an array

As far as I understand it, the sort function in the collection class can only be used to sort collections implementing the comparable interface.

You are supplying it a array of integers. You should probably wrap this around one of the know Wrapper classes such as Integer. Integer implements comparable.

Its been a long time since I have worked on some serious Java, however reading some matter on the sort function will help.

Cannot find R.layout.activity_main

There is probably an issue with the layout files, correct it and the auto generated class will appear.

Is mongodb running?

I find:

ps -ax | grep mongo

To be a lot more consistent. The value returned can be used to detect how many instances of mongod there are running

AngularJS - Multiple ng-view in single template

You cant have multiple ng-view. Below is my use case where I solved my requirement. I wanted to have tabbed behavior in my model dialog. I was facing issue as click on tabs having hyperlink which will invoke router links. I solved this using button and css for tabs. When user clicks on tab, it actually will not call any hyperlink which will always invoke the ng-router. When user click on tab it will call a method, where I dynamcilly load html. Below is the function on click of tab

self.submit = function(form) {
                $templateRequest('resources/items/employee/test_template.html').then(function(template){
                var compiledeHTML = $compile(template)($scope);
                $("#d").replaceWith(compiledeHTML);
});

User $templateRequest. In test_template.html page add your html content. This html content will be bind to your controller.

Create a txt file using batch file in a specific folder

This code written above worked for me as well. Although, you can use the code I am writing here:

@echo off

@echo>"d:\testing\dblank.txt

If you want to write some text to dblank.txt then add the following line in the end of your code

@echo Writing text to dblank.txt> dblank.txt

Retrieve version from maven pom.xml in code

Assuming you're using Java, you can:

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

  2. Set the value of some property in your .properties file using the standard Maven property for project version:

    foo.bar=${project.version}
    
  3. In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).

  4. In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>   
    </build>
    

You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

How to change the default background color white to something else in twitter bootstrap

I would not recommend changing the actual bootstrap CSS files. If you do not want to use Jako's first solution you can create a custom bootstrap style sheet with one of the available Bootstrap theme generator (Bootstrap theme generators). That way you can use 1 style sheet with all of the default Bootstrap CSS with just the one change to it that you want. With a Bootstrap theme generator you do not need to write any CSS. You only need to set the hex values for the color you want for the body (Scaffolding; bodyBackground).

How to copy Java Collections list

With Java 8 being null-safe, you could use the following code.

List<String> b = Optional.ofNullable(a)
                         .map(list -> (List<String>) new ArrayList<>(list))
                         .orElseGet(Collections::emptyList);

Or using a collector

List<String> b = Optional.ofNullable(a)
                         .map(List::stream)
                         .orElseGet(Stream::empty)
                         .collect(Collectors.toList())

Simple way to transpose columns and rows in SQL?

I'd like to point out few more solutions to transposing columns and rows in SQL.

The first one is - using CURSOR. Although the general consensus in the professional community is to stay away from SQL Server Cursors, there are still instances whereby the use of cursors is recommended. Anyway, Cursors present us with another option to transpose rows into columns.

  • Vertical expansion

    Similar to the PIVOT, the cursor has the dynamic capability to append more rows as your dataset expands to include more policy numbers.

  • Horizontal expansion

    Unlike the PIVOT, the cursor excels in this area as it is able to expand to include newly added document, without altering the script.

  • Performance breakdown

    The major limitation of transposing rows into columns using CURSOR is a disadvantage that is linked to using cursors in general – they come at significant performance cost. This is because the Cursor generates a separate query for each FETCH NEXT operation.

Another solution of transposing rows into columns is by using XML.

The XML solution to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

  • Vertical expansion

    Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

  • Horizontal expansion

    Unlike the PIVOT, newly added documents can be displayed without altering the script.

  • Performance breakdown

    In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

How to deploy a war file in Tomcat 7

1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file. There you go!

How to set up googleTest as a shared library on Linux

Update for Debian/Ubuntu

Google Mock (package: google-mock) and Google Test (package: libgtest-dev) have been merged. The new package is called googletest. Both old names are still available for backwards compatibility and now depend on the new package googletest.

So, to get your libraries from the package repository, you can do the following:

sudo apt-get install googletest -y
cd /usr/src/googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp googlemock/*.a googlemock/gtest/*.a /usr/lib

After that, you can link against -lgmock (or against -lgmock_main if you do not use a custom main method) and -lpthread. This was sufficient for using Google Test in my cases at least.

If you want the most current version of Google Test, download it from github. After that, the steps are similar:

git clone https://github.com/google/googletest
cd googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp lib/*.a /usr/lib

As you can see, the path where the libraries are created has changed. Keep in mind that the new path might be valid for the package repositories soon, too.

Instead of copying the libraries manually, you could use sudo make install. It "currently" works, but be aware that it did not always work in the past. Also, you don't have control over the target location when using this command and you might not want to pollute /usr/lib.

How to get a function name as a string?

To get the current function's or method's name from inside it, consider:

import inspect

this_function_name = inspect.currentframe().f_code.co_name

sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

To get the calling function's name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.


If also using mypy, it can complain that:

error: Item "None" of "Optional[FrameType]" has no attribute "f_code"

To suppress the above error, consider:

import inspect
import types
from typing import cast

this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

import numpy as np

mean_data = np.array([
[6.0, 315.0, 4.8123788544375692e-06],
[6.5, 0.0, 2.259217450023793e-06],
[6.5, 45.0, 9.2823565008402673e-06],
[6.5, 90.0, 8.309270169336028e-06],
[6.5, 135.0, 6.4709418114245381e-05],
[6.5, 180.0, 1.7227922423558414e-05],
[6.5, 225.0, 1.2308522579848724e-05],
[6.5, 270.0, 2.6905672894824344e-05],
[6.5, 315.0, 2.2727114437176048e-05]])

R = mean_data[:,0]
print R
print R.shape

EDIT

The reason why you had an invalid index error is the lack of a comma between mean_data and the values you wanted to add.

Also, np.append returns a copy of the array, and does not change the original array. From the documentation :

Returns : append : ndarray

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

So you have to assign the np.append result to an array (could be mean_data itself, I think), and, since you don't want a flattened array, you must also specify the axis on which you want to append.

With that in mind, I think you could try something like

mean_data = np.append(mean_data, [[ur, ua, np.mean(data[samepoints,-1])]], axis=0)

Do have a look at the doubled [[ and ]] : I think they are necessary since both arrays must have the same shape.

Merge two json/javascript arrays in to one array

You want the concat method.

var finalObj = json1.concat(json2);

What are MVP and MVC and what is the difference?

They each addresses different problems and can even be combined together to have something like below

The Combined Pattern

There is also a complete comparison of MVC, MVP and MVVM here

How to re-index all subarray elements of a multidimensional array?

To reset the keys of all arrays in an array:

$arr = array_map('array_values', $arr);

In case you just want to reset first-level array keys, use array_values() without array_map.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I encountered this error simply because I misspelled the spring.datasource.url value in the application.properties file and I was using postgresql:

Problem was: jdbc:postgres://localhost:<port-number>/<database-name>

Fixed to: jdbc:postgresql://localhost:<port-number>/<database-name>

NOTE: the difference is postgres & postgresql, the two are 2 different things.

Further causes and solutions may be found here

How to access full source of old commit in BitBucket?

Step 1

Step 1


Step 2

Step 2


Step 3

Step 3


Step 4

Step 4


Final Step

Final Step

CSS :not(:last-child):after selector

Remove the : before last-child and the :after and used

 ul li:not(last-child){
 content:' |';
}

Hopefully,it should work

SQLAlchemy ORDER BY DESCENDING?

Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.

.order_by("TableName.name desc")

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

Import Error: No module named numpy

pip3 may not refer to the python3 you use. run python3 -m pip install numpy instead.

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Git command to checkout any branch and overwrite local changes

The new git-switch command (starting in GIT 2.23) also has a flag --discard-changes which should help you. git pull might be necessary afterwards.

Warning: it's still considered to be experimental.

Write Array to Excel Range

In my case, the program queries the database which returns a DataGridView. I then copy that to an array. I get the size of the just created array and then write the array to an Excel spreadsheet. This code outputs over 5000 lines of data in about two seconds.

//private System.Windows.Forms.DataGridView dgvResults;
dgvResults.DataSource = DB.getReport();

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    var dgArray = new object[dgvResults.RowCount, dgvResults.ColumnCount+1];
    foreach (DataGridViewRow i in dgvResults.Rows)
    {
        if (i.IsNewRow) continue;
        foreach (DataGridViewCell j in i.Cells)
        {
            dgArray[j.RowIndex, j.ColumnIndex] = j.Value.ToString();
        }
    }

    Microsoft.Office.Interop.Excel.Range chartRange;

    int rowCount = dgArray.GetLength(0);
    int columnCount = dgArray.GetLength(1);
    chartRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[2, 1]; //I have header info on row 1, so start row 2
    chartRange = chartRange.get_Resize(rowCount, columnCount);
    chartRange.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dgArray);


    oXL.Visible = false;
    oXL.UserControl = false;
    string outputFile = "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

    oWB.SaveAs("c:\\temp\\"+outputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
}
catch (Exception ex)
{
    //...
}

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_

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Maximum number of rows of CSV data in excel sheet

In my memory, excel (versions >= 2007) limits the power 2 of 20: 1.048.576 lines.

Csv is over to this boundary, like ordinary text file. So you will be care of the transfer between two formats.

Sending JWT token in the headers with Postman

Somehow postman didn't work for me. I had to use a chrome extension called RESTED which did work.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Dive right it, make it a hobby, and have fun :)

Coming from an electronics background myself I can tell you that you should pick it up pretty quickly. And having an electronics background will give you a deeper understanding of the underlying hardware.

IMHO the root of information technology is electronics.

For example..

Think of objects as components.

The .NET framework is essentially drawers full of standard components.

For example you know what a 7400 (NAND gate) is capable of doing. You have a data sheet showing the pin outs and sample configurations. You don't typically care about the circuitry inside. Software objects are the same way. We have inputs and we have methods that do something to the inputs to produce predictable outputs. As developers we typically don't care how the object was written... just that it does what it says it will do.

You also know that you can build additional logic circuits by using two or more NAND gates. This of this as instantiation.

You also know that you can take a NAND gate and place it inside a circuit where you can modify the input signals coming in so the outputs have different behaviors. This is a crude example but you can think of this as inheritance.

I have also learned it helps to have a project to work on. It could be a hobbyist project or a work project. Start small, get something very basic working, and work up from there.

To answer your specific question on "what should I learn first".

1) Take your project you have in mind and break it into steps. For example... get a number from the user, add one to the number, display the result. Think of this as your design.

2) Learn basic C#. Write a simple console application that does something. Learn what an if statement is (this is all boolean logic so it should be somewhat familiar), learn about loops, learn about mathematical operations, learn about functions (subroutines). Play with simple file i/o (reading and writing text files). The basic C# can be thought of as your wiring and discrete components (resistors, caps, transistors, etc) to your chips (object).

3) Learn how to instantiate and use objects from the framework. You have already been doing this but now it's time to delve in further. For example... play with System.Console some more... try making the speaker beep. Also start looking for objects that you may want to use for database work.

4) Learn basic SQL. Lots of help and examples online. Pick a database you want to work with. I personally think MS Access is a great beginners database. I would not use it for multi-user or cross platform desktop applications... but it is a great single user database for Windows users... and it is a great way to learn the basics of SQL. There are other simple free databases available (Open Office has one for example) if you don't want to shell out $ for Access.

5) Expand your app to do something with a database.

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

Reset the database (purge all), then seed a database

If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all (or delete_all) in the seed.db file to clean out a table before your MyModel.create!(...) statements load the data. Then, you can redo the db:seed operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)

There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...

SVN remains in conflict?

If you have trouble resolving (like me) and you cannot delete and update the resources because you have made many changes on them, plus you are using eclipse subversive instead of native client, follow these steps:

  1. make a copy of your entire project dir
  2. perform team>disconnect within eclipse, and choose to delete the svn metadata
  3. then choose team>share project, and point to the very same folder that your project resides in
  4. choose yes, and commit everything (you may want to exclude some very local resources, like configuration files)
  5. if you have deleted or moved some resources prior to your first commit trial, delete those old resources (they should have doubled up, one in old location, one in new) and commit those deletions.

You're done.

Is there a way to programmatically minimize a window

Form myForm;
myForm.WindowState = FormWindowState.Minimized;

Converting ISO 8601-compliant String to java.util.Date

I faced the same problem and solved it by the following code .

 public static Calendar getCalendarFromISO(String datestring) {
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()) ;
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    try {
        Date date = dateformat.parse(datestring);
        date.setHours(date.getHours() - 1);
        calendar.setTime(date);

        String test = dateformat.format(calendar.getTime());
        Log.e("TEST_TIME", test);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return calendar;
}

Earlier I was using SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());

But later i found the main cause of the exception was the yyyy-MM-dd'T'HH:mm:ss.SSSZ ,

So i used

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());

It worked fine for me .

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

The key is "operating system error 5". Microsoft helpfully list the various error codes and values on their site

https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

ERROR_ACCESS_DENIED 5 (0x5) Access is denied.

What is the maximum length of a valid email address?

To help the confused rookies like me, the answer to "What is the maximum length of a valid email address?" is 254 characters.

If your application uses an email, just set your field to accept 254 characters or less and you are good to go.

You can run a bunch of tests on an email to see if it is valid here. http://isemail.info/

The RFC, or Request for Comments is a type of publication from the Internet Engineering Task Force (IETF) that defines 254 characters as the limit. Located here - https://tools.ietf.org/html/rfc5321#section-4.5.3

Casting interfaces for deserialization in JSON.NET

Use this class, for mapping abstract type to real type:

public class AbstractConverter<TReal, TAbstract> 
    : JsonConverter where TReal : TAbstract
{
    public override Boolean CanConvert(Type objectType)
        => objectType == typeof(TAbstract);

    public override Object ReadJson(JsonReader reader, Type type, Object value, JsonSerializer jser)
        => jser.Deserialize<TReal>(reader);

    public override void WriteJson(JsonWriter writer, Object value, JsonSerializer jser)
        => jser.Serialize(writer, value);
}

...and when deserialize:

var settings = new JsonSerializerSettings
{
    Converters = {
        new AbstractConverter<Thing, IThingy>(),
        new AbstractConverter<Thing2, IThingy2>()
    },
};

JsonConvert.DeserializeObject(json, type, settings);

How to find the lowest common ancestor of two nodes in any binary tree?

public class LeastCommonAncestor {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void createBinaryTree (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    private static class LCAData {
        TreeNode lca;
        int count;

        public LCAData(TreeNode parent, int count) {
            this.lca = parent;
            this.count = count;
        }
    }


    public int leastCommonAncestor(int n1, int n2) {
        if (root == null) {
            throw new NoSuchElementException("The tree is empty.");
        }

        LCAData lcaData = new LCAData(null, 0);
       // foundMatch (root, lcaData, n1,  n2);

        /**
         * QQ: boolean was returned but never used by caller.
         */
        foundMatchAndDuplicate (root, lcaData, n1,  n2, new HashSet<Integer>());

        if (lcaData.lca != null) {
            return lcaData.lca.item;
        } else {
            /**
             * QQ: Illegal thrown after processing function.
             */
            throw new IllegalArgumentException("The tree does not contain either one or more of input data. ");
        }
    }

//    /**
//     * Duplicate n1, n1         Duplicate in Tree
//     *      x                           x               => succeeds
//     *      x                           1               => fails.
//     *      1                           x               => succeeds by throwing exception
//     *      1                           1               => succeeds
//     */
//    private boolean foundMatch (TreeNode node, LCAData lcaData, int n1, int n2) {
//        if (node == null) {
//            return false;
//        }
//
//        if (lcaData.count == 2) {
//            return false;
//        }
//
//        if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
//            lcaData.count++;
//            return true;
//        }
//
//        boolean foundInCurrent = false;
//        if (node.item == n1 || node.item == n2) {
//            lcaData.count++;
//            foundInCurrent = true;
//        }
//
//        boolean foundInLeft = foundMatch(node.left, lcaData, n1, n2);
//        boolean foundInRight = foundMatch(node.right, lcaData, n1, n2);
//
//        if ((foundInLeft && foundInRight) || (foundInCurrent && foundInRight) || (foundInCurrent && foundInLeft)) {
//            lcaData.lca = node;
//            return true; 
//        }
//        return foundInCurrent || (foundInLeft || foundInRight);
//    }


    private boolean foundMatchAndDuplicate (TreeNode node, LCAData lcaData, int n1, int n2, Set<Integer> set) {
        if (node == null) {
            return false;
        }

        // when both were found
        if (lcaData.count == 2) {
            return false;
        }

        // when only one of them is found
        if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
            if (!set.contains(node.item)) {
                lcaData.count++;
                return true;
            }
        }

        boolean foundInCurrent = false;  
        // when nothing was found (count == 0), or a duplicate was found (count == 1)
        if (node.item == n1 || node.item == n2) {
            if (!set.contains(node.item)) {
                set.add(node.item);
                lcaData.count++;
            }
            foundInCurrent = true;
        }

        boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set);
        boolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set);

        if (((foundInLeft && foundInRight) || 
                (foundInCurrent && foundInRight) || 
                    (foundInCurrent && foundInLeft)) &&
                        lcaData.lca == null) {
            lcaData.lca = node;
            return true; 
        }
        return foundInCurrent || (foundInLeft || foundInRight);
    }




    public static void main(String args[]) {
        /**
         * Binary tree with unique values.
         */
        Integer[] arr1 = {1, 2, 3, 4, null, 6, 7, 8, null, null, null, null, 9};
        LeastCommonAncestor commonAncestor = new LeastCommonAncestor();
        commonAncestor.createBinaryTree(arr1);

        int ancestor = commonAncestor.leastCommonAncestor(2, 4);
        System.out.println("Expected 2, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 7);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 6);
        System.out.println("Expected 1, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 1);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(3, 8);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(7, 9);
        System.out.println("Expected 3, actual " +ancestor);

        // duplicate request 
        try {
            ancestor = commonAncestor.leastCommonAncestor(7, 7);
        } catch (Exception e) {
            System.out.println("expected exception");
        }

        /**
         * Binary tree with duplicate values.
         */
        Integer[] arr2 = {1, 2, 8, 4, null, 6, 7, 8, null, null, null, null, 9};
        commonAncestor = new LeastCommonAncestor();
        commonAncestor.createBinaryTree(arr2);

        // duplicate requested
        ancestor = commonAncestor.leastCommonAncestor(8, 8);
        System.out.println("Expected 1, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(4, 8);
        System.out.println("Expected 4, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(7, 8);
        System.out.println("Expected 8, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 6);
        System.out.println("Expected 1, actual " + ancestor);

         ancestor = commonAncestor.leastCommonAncestor(8, 9);  
        System.out.println("Expected 8, actual " +ancestor); // failed.
    }
}

Convert Json Array to normal Java list

Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();


                        adapter.notifyDataSetChanged();

...

Group list by values

values = set(map(lambda x:x[1], mylist))
newlist = [[y[0] for y in mylist if y[1]==x] for x in values]

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

This is an old post, but if IE is giving you trouble. Change your GET requests to POST and IE will no longer cache them.

I spent way too much time figuring this out the hard way. Hope it helps.

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

Django - Reverse for '' not found. '' is not a valid view function or pattern name

I was receiving the same error when not specifying the app name before pattern name. In my case:

app-name : Blog

pattern-name : post-delete

reverse_lazy('Blog:post-delete') worked.

How to remove html special chars?

Use html_entity_decode to convert HTML entities.

You'll need to set charset to make it work correctly.

Spring Could not Resolve placeholder

Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:

  • src/main/resource/config
  • src/test/resource/config

containing the same property you are referring

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.

Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group that contains thousands of Users:

  • How would you access them? With so many Users, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.

  • How would you add new Users to the Group? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group. However, if you want to keep objects in memory consistent, you also need to add User to Group.users. But it would make Hibernate to fetch all elements of Group.users from the database!

So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.

See also:

Rails: How to run `rails generate scaffold` when the model already exists?

You can make use of scaffold_controller and remember to pass the attributes of the model, or scaffold will be generated without the attributes.

rails g scaffold_controller User name email
# or
rails g scaffold_controller User name:string email:string

This command will generate following files:

create  app/controllers/users_controller.rb
invoke  haml
create    app/views/users
create    app/views/users/index.html.haml
create    app/views/users/edit.html.haml
create    app/views/users/show.html.haml
create    app/views/users/new.html.haml
create    app/views/users/_form.html.haml
invoke  test_unit
create    test/controllers/users_controller_test.rb
invoke  helper
create    app/helpers/users_helper.rb
invoke    test_unit
invoke  jbuilder
create    app/views/users/index.json.jbuilder
create    app/views/users/show.json.jbuilder

GROUP BY + CASE statement

can you please try this: replace the case statement with the below one

Sum(CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END) as Count,

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

OR operator in switch-case?

foreach (array('one', 'two', 'three') as $v) {
    switch ($v) {
        case (function ($v) {
            if ($v == 'two') return $v;
            return 'one';
        })($v):
            echo "$v min \n";
            break;


    }
}

this works fine for languages supporting enclosures

What does @media screen and (max-width: 1024px) mean in CSS?

If your media query condition is true then your CSS with that condition will work. That means CSS within your media query's condition pixel size will effect, or else if the condition will fail that mean if the device's width is greater than 1024px than your CSS will not work.Because your media query condition false.

max-width is your max CSS limit till that width.

Python Flask, how to set content type

from flask import Flask, render_template, make_response
app = Flask(__name__)

@app.route('/user/xml')
def user_xml():
    resp = make_response(render_template('xml/user.html', username='Ryan'))
    resp.headers['Content-type'] = 'text/xml; charset=utf-8'
    return resp

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Using true and false in C

Any int other than zero is true; false is zero. That way code like this continues to work as expected:

int done = 0;   // `int` could be `bool` just as well

while (!done)
{
     // ...
     done = OS_SUCCESS_CODE == some_system_call ();
}

IMO, bool is an overrated type, perhaps a carry over from other languages. int works just fine as a boolean type.

How to add label in chart.js for pie chart

EDIT: http://jsfiddle.net/nCFGL/223/ My Example.

You should be able to like follows:

var pieData = [{
    value: 30,
    color: "#F38630",
    label: 'Sleep',
    labelColor: 'white',
    labelFontSize: '16'
  },
  ...
];

Include the Chart.js located at:

https://github.com/nnnick/Chart.js/pull/35

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

My silly mistake was this: change != to ==

if(convertView != null) { // <---- HERE 
                LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
                convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);

                TextView textView = convertView.findViewById(R.id.board_name_tv);
                ImageView imageView = convertView.findViewById(R.id.board_imageview);

                textView.setText(text_list.get(position));
                imageView.setImageDrawable(imageAddressList.get(position));

                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("MESSAGE", text_list.get(pos));
                        setResult(98, intent);
                        finish();
                    }
                });
            }
return convertView;

How to display Oracle schema size with SQL query?

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
    FROM DBA_SEGMENTS DS
    WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
    GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;

Java, How to add library files in netbeans?

In Netbeans 8.2

1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.

2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.

3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!

UILabel text margin

I think UILabel class have no method for setting margin. Why you not set the position of Label at required place?

See below code:

UILabel *label = [[UILabel alloc] init];
label.text = @"This is label";
label.frame = CGRectMake(0,0,100,100);

if from interface builder then just position Label by following:

yourLabel.frame = CGRectMake(0,0,100,100);

How do I include a pipe | in my linux find -exec command?

the solution is easy: execute via sh

... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.

How to add a default "Select" option to this ASP.NET DropDownList control?

I have tried with following code. it's working for me fine

ManageOrder Order = new ManageOrder();
Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString());
Organization.DataValueField = "OrganisationID";
Organization.DataTextField = "OrganisationName";                
Organization.DataBind();                
Organization.Items.Insert(0, new ListItem("Select Organisation", "0"));

Fast query runs slow in SSRS

I had the same problem, here is my description of the problem

"I created a store procedure which would generate 2200 Rows and would get executed in almost 2 seconds however after calling the store procedure from SSRS 2008 and run the report it actually never ran and ultimately I have to kill the BIDS (Business Intelligence development Studio) from task manager".

What I Tried: I tried running the SP from reportuser Login but SP was running normal for that user as well, I checked Profiler but nothing worked out.

Solution:

Actually the problem is that even though SP is generating the result but SSRS engine is taking time to read these many rows and render it back. So I added WITH RECOMPILE option in SP and ran the report .. this is when miracle happened and my problem got resolve.

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

Call to undefined function mysql_query() with Login

You are mixing mysql and mysqli

Change these lines:

$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);

to

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

How do I send a file in Android from a mobile device to server using http?

Easy, you can use a Post request and submit your file as binary (byte array).

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

ALTER COLUMN in sqlite

While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT 
NULL);**  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
Error: BOOKS.publication_date may not be NULL  
sqlite> **PRAGMA writable_schema = 1;**  
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT 
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**  
sqlite> **PRAGMA writable_schema = 0;**  
sqlite> **.q**  

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
sqlite> **.q**  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

Apply CSS Style to child elements

The > selector matches direct children only, not descendants.

You want

div.test th, td, caption {}

or more likely

div.test th, div.test td, div.test caption {}

Edit:

The first one says

  div.test th, /* any <th> underneath a <div class="test"> */
  td,          /* or any <td> anywhere at all */
  caption      /* or any <caption> */

Whereas the second says

  div.test th,     /* any <th> underneath a <div class="test"> */
  div.test td,     /* or any <td> underneath a <div class="test"> */
  div.test caption /* or any <caption> underneath a <div class="test">  */

In your original the div.test > th says any <th> which is a **direct** child of <div class="test">, which means it will match <div class="test"><th>this</th></div> but won't match <div class="test"><table><th>this</th></table></div>

Restart android machine

Have you tried simply 'reboot' with adb?

  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:

 adb shell <command>

The official docs can be found here.

Resize svg when window is resized in d3.js

Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.

Here is how I did it:

_x000D_
_x000D_
d3.select("div#chartId")_x000D_
   .append("div")_x000D_
   // Container class to make it responsive._x000D_
   .classed("svg-container", true) _x000D_
   .append("svg")_x000D_
   // Responsive SVG needs these 2 attributes and no width and height attr._x000D_
   .attr("preserveAspectRatio", "xMinYMin meet")_x000D_
   .attr("viewBox", "0 0 600 400")_x000D_
   // Class to make it responsive._x000D_
   .classed("svg-content-responsive", true)_x000D_
   // Fill with a rectangle for visualization._x000D_
   .append("rect")_x000D_
   .classed("rect", true)_x000D_
   .attr("width", 600)_x000D_
   .attr("height", 400);
_x000D_
.svg-container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%; /* aspect ratio */_x000D_
  vertical-align: top;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.svg-content-responsive {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 10px;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
svg .rect {_x000D_
  fill: gold;_x000D_
  stroke: steelblue;_x000D_
  stroke-width: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.

More info / tutorials:

http://thenewcode.com/744/Make-SVG-Responsive

http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

ArrayList initialization equivalent to array initialization

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

How to use EOF to run through a text file in C?

I would suggest you to use fseek-ftell functions.

FILE *stream = fopen("example.txt", "r");

if(!stream) {
    puts("I/O error.\n");
    return;
}

fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);

while(1) {

    if(ftell(stream) == size) {
        break;
    }

    /* INSERT ROUTINE */

}

fclose(stream);

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

C++ Best way to get integer division and remainder

On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.

C++ code:

void foo(int a, int b, int* c, int* d)
{
  *c = a / b;
  *d = a % b;
}

x86 code:

__Z3fooiiPiS_:
LFB4:
    movq    %rdx, %r8
    movl    %edi, %edx
    movl    %edi, %eax
    sarl    $31, %edx
    idivl   %esi
    movl    %eax, (%r8)
    movl    %edx, (%rcx)
    ret

Eclipse: stop code from running (java)

For newer versions of Eclipse:

  1. open the Debug perspective (Window > Open Perspective > Debug)

  2. select process in Devices list (bottom right)

  3. Hit Stop button (top right of Devices pane)

Fast Bitmap Blur For Android SDK

This is for all people who need to increase the radius of ScriptIntrinsicBlur to obtain a harder gaussian blur.

Instead of to put the radius more than 25, you can scale down the image and get the same result. I wrote a class called GaussianBlur. Below you can see how to use, and the whole class implementation.

Usage:

GaussianBlur gaussian = new GaussianBlur(context);
gaussian.setMaxImageSize(60);
gaussian.setRadius(25); //max

Bitmap output = gaussian.render(<your bitmap>,true);
Drawable d = new BitmapDrawable(getResources(),output);

Class:

 public class GaussianBlur {
    private final int DEFAULT_RADIUS = 25;
    private final float DEFAULT_MAX_IMAGE_SIZE = 400;

    private Context context;
    private int radius;
    private float maxImageSize;

    public GaussianBlur(Context context) {
    this.context = context;
    setRadius(DEFAULT_RADIUS);
    setMaxImageSize(DEFAULT_MAX_IMAGE_SIZE);
    } 

    public Bitmap render(Bitmap bitmap, boolean scaleDown) {
    RenderScript rs = RenderScript.create(context);

    if (scaleDown) {
        bitmap = scaleDown(bitmap);
    }

    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);

    Allocation inAlloc = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE);
    Allocation outAlloc = Allocation.createFromBitmap(rs, output);

    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, inAlloc.getElement()); // Element.U8_4(rs));
    script.setRadius(getRadius());
    script.setInput(inAlloc);
    script.forEach(outAlloc);
    outAlloc.copyTo(output);

    rs.destroy();

    return output;
}

public Bitmap scaleDown(Bitmap input) {
    float ratio = Math.min((float) getMaxImageSize() / input.getWidth(), (float) getMaxImageSize() / input.getHeight());
    int width = Math.round((float) ratio * input.getWidth());
    int height = Math.round((float) ratio * input.getHeight());

    return Bitmap.createScaledBitmap(input, width, height, true);
}

public int getRadius() {
    return radius;
}

public void setRadius(int radius) {
    this.radius = radius;
}

public float getMaxImageSize() {
    return maxImageSize;
}

public void setMaxImageSize(float maxImageSize) {
    this.maxImageSize = maxImageSize;
}
    }

PostgreSQL database service

You might get a more descriptive error message if you tried to start the service from command line using this command:

"C:\Program Files\PostgreSQL\9.5\bin\pg_ctl.exe" start -N "postgresql-x64-9.5" 
  -D "C:\Program Files\PostgreSQL\9.5\data" -w

The log file would be at C:\Program Files\PostgreSQL\9.5\data\pg_log. Note that paths and service name might be different depending on your installation.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

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

Hope you have key field is two tables.

 UPDATE tblindiantime t
   SET CountryName = (SELECT c.BusinessCountry 
                     FROM contacts c WHERE c.Key = t.Key 
                     )

What is the best way to determine a session variable is null or empty in C#?

I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

string Name
{
   get 
   {
       if(Session["Name"] == Null)
           Session["Name"] = "Default value";
       return (string)Session["Name"];
   }
   set { Session["Name"] = value; }
}

}

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

IF function with 3 conditions

=if([Logical Test 1],[Action 1],if([Logical Test 2],[Action 1],if([Logical Test 3],[Action 3],[Value if all logical tests return false])))

Replace the components in the square brackets as necessary.

Attempt to set a non-property-list object as an NSUserDefaults

Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

The Pref struct is custom wrapper around the UserDefaults standard object.

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

So you can use it this way:

Pref.user?.name = "John"

if let user = Pref.user {...

how to return index of a sorted list?

How about

l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]

Redis: How to access Redis log file

vi /usr/local/etc/redis.conf

Look for dir, logfile

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/



# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null 
logfile "redis_log"

So the log file is created at /usr/local/var/db/redis/redis_log with the name redis_log

You can also try MONITOR command from redis-cli to review the number of commands executed.

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

Calculate the mean by group

Adding alternative base R approach, which remains fast under various cases.

rowsummean <- function(df) {
  rowsum(df$speed, df$dive) / tabulate(df$dive)
}

Borrowing the benchmarks from @Ari:

10 rows, 2 groups

res1

10 million rows, 10 groups

res2

10 million rows, 1000 groups

res3

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.

http://localhost:8080/env-vars.html/

Just replace localhost with your Jenkins hostname, if its different

How can I get my Twitter Bootstrap buttons to right align?

you can also use blank columns to give spaces on left

like

<div class="row">
    <div class="col-md-8"></div>  <!-- blank space increase or decrease it by column # -->
        <div class="col-md-4">
            <button id="saveedit" name="saveedit" class="btn btn-success">Save</button>
        </div>
</div>

Demo :: Jsfiddle demo

How to get row count in sqlite using Android?

Once you get the cursor you can do

Cursor.getCount()

Button that refreshes the page on click

<a onClick="window.location.reload()">Refresh</a>

This really works perfect for me.

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

How to send a model in jQuery $.ajax() post request to MVC controller method

I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

Have a look at the doc here.. Ajax serialize

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

How to get an object's properties in JavaScript / jQuery?

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each() method:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

A project with an Output Type of Class Library cannot be started directly

The project is a class library. It cannot be run or debugged without an executable project (F5 doesn't work!!!). You can only build the project (Ctrl+Shift+B).

If you want to debug the code add a console application project (set it as the start up project) to the solution and add the reference to the library.

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

Define variable to use with IN operator (T-SQL)

slight improvement on @LukeH, there is no need to repeat the "INSERT INTO": and @realPT's answer - no need to have the SELECT:

DECLARE @MyList TABLE (Value INT) 
INSERT INTO @MyList VALUES (1),(2),(3),(4)

SELECT * FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)

How to get the first 2 letters of a string in Python?

All previous examples will raise an exception in case your string is not long enough.

Another approach is to use 'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

Python: Best way to add to sys.path relative to the current running script

When we try to run python file with path from terminal.

import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)

Save the file (test.py).

Runing system.

Open terminal and go the that dir where is save file. then write

python test.py "/home/saiful/Desktop/bird.jpg"

Hit enter

Output:

File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg

SQL: ... WHERE X IN (SELECT Y FROM ...)

SELECT Customers.* 
  FROM Customers 
 WHERE NOT EXISTS (
       SELECT *
         FROM SUBSCRIBERS AS s
         JOIN s.Cust_ID = Customers.Customer_ID) 

When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, the query can use an index within the sub-query.

How do I fit an image (img) inside a div and keep the aspect ratio?

you can use class "img-fluid" for newer version i.e Bootstrap v4.

and can use class "img-responsive" for older version like Bootstrap v3.

Usage:-

img tag with :-

class="img-fluid"

src="..."

C++ pass an array by reference

8.3.5.8 If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed

java IO Exception: Stream Closed

Don't call write.close() in writeToFile().

Regular expression to extract URL from an HTML link

this regex can help you, you should get the first group by \1 or whatever method you have in your language.

href="([^"]*)

example:

<a href="http://www.amghezi.com">amgheziName</a>

result:

http://www.amghezi.com

How to securely save username/password (local)?

DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.

Bootstrap table striped: How do I change the stripe background colour?

I found this checkerboard pattern (as a subset of the zebra stripe) to be a pleasant way to display a two-column table. This is written using LESS CSS, and keys all colors off the base color.

@base-color: #0000ff;
@row-color: lighten(@base-color, 40%);    
@other-row: darken(@row-color, 10%);

tbody {
    td:nth-child(odd) { width: 45%; }
    tr:nth-child(odd) > td:nth-child(odd) {
        background: darken(@row-color, 0%); }
    tr:nth-child(odd) > td:nth-child(even) {
        background: darken(@row-color, 7%); }
    tr:nth-child(even) > td:nth-child(odd) {
        background: darken(@other-row, 0%); }
    tr:nth-child(even) > td:nth-child(even) {
        background: darken(@other-row, 7%); }
}

Note I've dropped the .table-striped, but doesn't seem to matter.

Looks like: enter image description here

How do I run a PowerShell script when the computer starts?

You could create a Scheduler Task that runs automatically on the start, even when the user is not logged in:

schtasks /create /tn "FileMonitor" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file C:\Doc\Files\FileMonitor.ps1"

Run this command once from a PowerShell as Admin and it will create a schedule task for you. You can list the task like this:

schtasks /Query /TN "FileMonitor" /V /FO List

or delete it

schtasks /Delete /TN "FileMonitor"

CSS force new line

or you can use:

a {
    display: inline-block;
  }

Xcode Error: "The app ID cannot be registered to your development team."

I had the issue with different development teams. I just checked the schema signings and picked the correct development team for the schemas that I needed:

Ss from Xcode

How do I restart my C# WinForm Application?

Here's my 2 cents:

The sequence Start New Instance->Close Current Instance should work even for the applications that don't allow running multiple copies simultaneously as in this case the new instance may be passed a command-line argument which will indicate that there is a restart in progress so checking for other instances running will not be necessary. Waiting for the first instance to actually finish my be implemented too if it's absolutely imperative that no two intstances are running in parallel.

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

How to disable compiler optimizations in gcc?

For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.

See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html

Hive: how to show all partitions of a table?

hive> show partitions table_name;

Position a div container on the right side

This works for me.

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>

Capturing console output from a .NET application (C#)

This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.

Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();    

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();

What are the differences between Deferred, Promise and Future in JavaScript?

  • A promise represents a value that is not yet known
  • A deferred represents work that is not yet finished

A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.

Reference

drop down list value in asp.net

You can try this

your_ddl_id.Items.Insert(0,new ListItem("Select","");

jQuery get html of container including the container itself

I like to use this;

$('#container').prop('outerHTML');

Getting the parent div of element

You're looking for parentNode, which Element inherits from Node:

parentDiv = pDoc.parentNode;

Handy References:

  • DOM2 Core specification - well-supported by all major browsers
  • DOM2 HTML specification - bindings between the DOM and HTML
  • DOM3 Core specification - some updates, not all supported by all major browsers
  • HTML5 specification - which now has the DOM/HTML bindings in it

Clone contents of a GitHub repository (without the folder itself)

If the folder is not empty, a slightly modified version of @JohnLittle's answer worked for me:

git init
git remote add origin https://github.com/me/name.git
git pull origin master

As @peter-cordes pointed out, the only difference is using https protocol instead of git, for which you need to have SSH keys configured.

Java ArrayList how to add elements at the beginning

import java.util.*:
public class Logic {
  List<String> list = new ArrayList<String>();
  public static void main(String...args) {
  Scanner input = new Scanner(System.in);
    Logic obj = new Logic();
      for (int i=0;i<=20;i++) {
        String string = input.nextLine();
        obj.myLogic(string);
        obj.printList();
      }
 }
 public void myLogic(String strObj) {
   if (this.list.size()>=10) {
      this.list.remove(this.list.size()-1);
   } else {
     list.add(strObj); 
   }
 }
 public void printList() {
 System.out.print(this.list);
 }
}

Importing a Maven project into Eclipse from Git

You should note that putting generated metadata under version control (let it be git or any other scm), is not a very good idea if there are more than one developer working on the codebase. Two developers may have a totally different project or classpath setup. Just as a heads up in case you intends to share the code at some time...

Maven: How to rename the war file for the project?

You need to configure the war plugin:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warName>bird.war</warName>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

More info here

Fit cell width to content

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

What do 3 dots next to a parameter type mean in Java?

Adding to the other well-written answers, an advantage of varagrs I found useful is that, when I call a method with array as a parameter type, it takes away the pain of creating an array; add elements and then send it. Instead, I can just call the method with as many values as I want; from zero to many.

Choosing a file in Python with simple Dialog

I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:

https://stackoverflow.com/a/9319832

The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.

Fastest way to tell if two files have the same contents in Unix/Linux?

I believe cmp will stop at the first byte difference:

cmp --silent $old $new || echo "files are different"

Copy files from one directory into an existing directory

Depending on some details you might need to do something like this:

r=$(pwd)
case "$TARG" in
    /*) p=$r;;
    *) p="";;
    esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"

... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

The extra fussing is to handle relative or absolute targets.

(This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

When to use static methods

No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

_x000D_
_x000D_
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
_x000D_
_x000D_
_x000D_

How to combine results of two queries into a single dataset

The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2

If you had, for example, the following data:

col1  col2
a     1
b     2

col3  col4
y     98
z     99

You would end up with the following:

col1  col2  col3  col4
a     1     y     98
a     1     z     99
b     2     y     98
b     2     z     99

Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField

That would pull things together for you into however the data is related, giving you your result.

What is the difference between using constructor vs getInitialState in React / React Native?

Constructor The constructor is a method that's automatically called during the creation of an object from a class. ... Simply put, the constructor aids in constructing things. In React, the constructor is no different. It can be used to bind event handlers to the component and/or initializing the local state of the component.Jan 23, 2019

getInitialState In ES6 classes, you can define the initial state by assigning this.state in the constructor:

Look at this example

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

How can I close a login form and show the main form without my application closing?

The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.

The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:

static void Main()
{
    LoginForm fLogin = new LoginForm();
    if (fLogin.ShowDialog() == DialogResult.OK)
    {
        Application.Run(new MainForm());
    }
    else
    {
        Application.Exit();
    }
}

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to print the values of slices

fmt.Printf() is fine, but sometimes I like to use pretty print package.

import "github.com/kr/pretty"
pretty.Print(...)

Regular expression that doesn't contain certain string

I'm not sure it's a standard construct, but I think you should have a look on "negative lookahead" (which writes : "?!", without the quotes). It's far easier than all answers in this thread, including the accepted one.

Example : Regex : "^(?!123)[0-9]*\w" Captures any string beginning by digits followed by letters, UNLESS if "these digits" are 123.

http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx#grouping_constructs (microsoft page, but quite comprehensive) for lookahead / lookbehind

PS : it works well for me (.Net). But if I'm wrong on something, please let us know. I find this construct very simple and effective, so I'm surprised of the accepted answer.

How do I make a transparent canvas in html5?

Canvases are transparent by default.

Try setting a page background image, and then put a canvas over it. If nothing is drawn on the canvas, you can fully see the page background.

Think of a canvas as like painting on a glass plate.

How to urlencode a querystring in Python?

In Python 3, this worked with me

import urllib

urllib.parse.quote(query)

How to change the name of a Django app?

If you use Pycharm, renaming an app is very easy with refactoring(Shift+F6 default) for all project files.
But make sure you delete the __pycache__ folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you'll have to rename OldNameConfig(AppConfig): in apps.py of your renamed app in addition.

If you do not want to lose data of your database, you'll have to manually do it with query in database like the aforementioned answer.

Java best way for string find and replace?

Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.

You can view the StringUtils API at the previously linked website.

"Don't reinvent the wheel"

How to use ConcurrentLinkedQueue?

This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:

for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}

This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.

MySQL LIKE IN()?

You can get desired result with help of Regular Expressions.

SELECT fiberbox from fiberbox where fiberbox REGEXP '[1740|1938|1940]';

We can test the above query please click SQL fiddle

SELECT fiberbox from fiberbox where fiberbox REGEXP '[174019381940]';

We can test the above query please click SQL fiddle