Programs & Examples On #Morphia

Morphia is a lightweight type-safe library for mapping Java objects to/from MongoDB.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

Cannot find module cv2 when using OpenCV

I solve this by run code pip install opencv_contrib_python

illegal character in path

try

"C:/Program Files (x86)/test software/myapp/demo.exe"

Importing modules from parent folder

I made this library to do this.

https://github.com/fx-kirin/add_parent_path

# Just add parent path
add_parent_path(1)

# Append to syspath and delete when the exist of with statement.
with add_parent_path(1):
   # Import modules in the parent path
   pass

Uploading a file in Rails

Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field to get the file,

In controller,

 @person = Person.new(person_params)

Here person_params return whitelisted params[:person] (define yourself)

Save file as,

dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")

Note, Add this path in .gitignore & if you want to use this file again add this path asset_pathan of application by application.rb

Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets

note: Storing files like this will increase the size of the application, better to store in the database using paperclip.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

How to check the gradle version in Android Studio?

I know this is really old and most of the folks have already answered it right. Here are at least two ways you can find out the gradle version (not the gradle plugin version) by selecting one of the following on project tab on left:

  1. Android > Gradle Scripts > gradle-wrapper.properties (Gradle Version) > distributionURL
  2. Project > .gradle > x.y.z <--- this is your gradle version

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

If your repository contains a few files which are removed from master:

  1. git checkout master
  2. git fetch origin
  3. git reset --hard origin/master
  4. git checkout -b newbranch

Can functions be passed as parameters?

Yes Go does accept first-class functions.

See the article "First Class Functions in Go" for useful links.

concatenate variables

set ROOT=c:\programs 
set SRC_ROOT=%ROOT%\System\Source

Change WPF window background image in C# code

Uri resourceUri = new Uri(@"/cCleaner;component/Images/cleanerblack.png", UriKind.Relative);
            StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
            BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
            var brush = new ImageBrush();
            brush.ImageSource = temp;
            frame8.Background = brush;

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How can the default node version be set using NVM?

Alert: This answer is for MacOS only

Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0

And, v15.4.0 is default

> nvm list
       v13.10.1
->      v15.4.0
         system
default -> 15.4.0 (-> v15.4.0)

And, you want to switch the default to v13.10.1

Follow these steps on your Mac terminal:

  1. Run the command:

    nvm alias default 13.10.1

This will make the default point to v13.10.1 as...

default -> 13.10.1 (-> v13.10.1)
  1. Open new instance of terminal. Now check the node version here as...

node -v

You will get...

v13.10.1
  1. nvm list will also show the new default version.

    nvm list

Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v

Add Foreign Key to existing table

Simply use this query, I have tried it as per my scenario and it works well

ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);

How to get current moment in ISO 8601 format with date, hour, and minute?

Try This,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
        String date=sdf.format (new Date() );

Its For ISO 8601 format

Rollback to an old Git commit in a public repo

Step 1: fetch list of commits:

git log

You'll get list like in this example:

[Comp:Folder User$ git log
commit 54b11d42e12dc6e9f070a8b5095a4492216d5320
Author: author <[email protected]>
Date:   Fri Jul 8 23:42:22 2016 +0300

This is last commit message

commit fd6cb176297acca4dbc69d15d6b7f78a2463482f
Author: author <[email protected]>
Date:   Fri Jun 24 20:20:24 2016 +0300

This is previous commit message

commit ab0de062136da650ffc27cfb57febac8efb84b8d
Author: author <[email protected]>
Date:   Thu Jun 23 00:41:55 2016 +0300

This is previous previous commit message
...

Step 2: copy needed commit hash and paste it for checkout:

git checkout fd6cb176297acca4dbc69d15d6b7f78a2463482f

That's all.

BATCH file asks for file or folder

Actually xcopy does not ask you if the original file exists, but if you want to put it in a new folder named Shapes.atc, or in the folder Support (which is what you want.

To prevent xcopy from asking this, just tell him the destination folder, so there's no ambiguity:

xcopy /s/y "J:\Old path\Shapes.atc" "C:\Documents and Settings\his name\Support"

If you want to change the filename in destination just use copy (which is more adapted than xcopy when copying files):

copy /y "J:\Old path\Shapes.atc" "C:\Documents and Settings\his name\Support\Shapes-new.atc

What does @@variable mean in Ruby?

@ - Instance variable of a class
@@ - Class variable, also called as static variable in some cases

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. If one object instance changes the value of the variable, that new value will essentially change for all other object instances.

Another way of thinking of thinking of class variables is as global variables within the context of a single class. Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time

Node.js: Python not found exception due to node-sass and node-gyp

I had to:

Delete node_modules
Uninstall/reinstall node
npm install [email protected]

worked fine after forcing it to the right sass version, according to the version said to be working with the right node.

NodeJS  Minimum node-sass version   Node Module
Node 12 4.12+   72
Node 11 4.10+   67
Node 10 4.9+    64
Node 8  4.5.3+  57

There was lots of other errors that seemed to be caused by the wrong sass version defined.

Passing a method as a parameter in Ruby

You can pass a method as parameter with method(:function) way. Below is a very simple example:

def double(a)
  return a * 2 
end
=> nil

def method_with_function_as_param( callback, number) 
  callback.call(number) 
end 
=> nil

method_with_function_as_param( method(:double) , 10 ) 
=> 20

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

I was presented with the same issue. The cause for me was Grunt concatenating my JavaScript file.

I was using a ;\n as a separator which caused the path to the source map to 404.

So dev tools was looking for jquery.min.map; instead of jquery.min.map.

I know that isn't the answer to the original question, but I am sure there are others out there with a similar Grunt configuration.

How to search by key=>value in a multidimensional array in PHP

function findKey($tab, $key){
    foreach($tab as $k => $value){ 
        if($k==$key) return $value; 
        if(is_array($value)){ 
            $find = findKey($value, $key);
            if($find) return $find;
        }
    }
    return null;
}

How do I kill the process currently using a port on localhost in Windows?

Step 1:

Open up cmd.exe (note: you may need to run it as an administrator, but this isn't always necessary), then run the below command:

netstat -ano | findstr :<PORT>

(Replace <PORT> with the port number you want, but keep the colon)

The area circled in red shows the PID (process identifier). Locate the PID of the process that's using the port you want.

Step 2:

Next, run the following command:

taskkill /PID <PID> /F

(No colon this time)

Lastly, you can check whether the operation succeeded or not by re-running the command in "Step 1". If it was successful you shouldn't see any more search results for that port number.

How do I create a constant in Python?

All of the answers given are essentially of two types:

  1. Create some sort of object for which you can create attributes which cannot be changed once defined.
  2. Use a convention (like writing constants in all UPPERCASE or, for Python 3.8, use the final qualifier to indicate that you intend one or more names to be a constant.

They can be summarized as saying "you cannot do what you ask using Python".

However, there is actually a way to create a module with true constants. The code to do so is rather involved, and I will only give an outline of what is needed to do as it is already available under an open source license.

  1. Use an import hook to enable the creation of a custom module. The versatile code I use for this is found here.
  2. Create a special dict which allows adding items that conform to your chosen pattern (for example, names in all UPPERCASE) only once and prevent such names to have their values changed. For this, you will need to define your own methods such as __setitem__, __delitem__, etc. The code for such a dict (such as found in this file, which is over 250 lines) is approximately 100 lines long.
  3. The dict for a normal Python module cannot be modified. So, when creating the module, you need to execute the code in your special dict first, and then use its content to update the module's dict.
  4. To prevent modifications of the values of the contants from outside of the module (i.e. monkeypatching), you can replace the __class__ of the module by a custom one with the __setattr__ and __delattr__ method redefined.

The documentation about this example can be found here. It probably should be updated to reflect the number of answers given to this question.

How can I create a copy of an Oracle table without copying the data?

If one needs to create a table (with an empty structure) just to EXCHANGE PARTITION, it is best to use the "..FOR EXCHANGE.." clause. It's available only from Oracle version 12.2 onwards though.

CREATE TABLE t1_temp FOR EXCHANGE WITH TABLE t1;

This addresses 'ORA-14097' during the 'exchange partition' seamlessly if table structures are not exactly copied by normal CTAS operation. I have seen Oracle missing some of the "DEFAULT" column and "HIDDEN" columns definitions from the original table.

ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION

See this for further read...

How to Correctly handle Weak Self in Swift Blocks with Arguments

As of swift 4.2 we can do:

_ = { [weak self] value in
    guard let self = self else { return }
    print(self) // will never be nil
}()

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Just Follow Simple 1-2-3 Steps :

1) Go to Taskbar

2) Click on WAMP icon (Left Click)

enter image description here

3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !

enter image description here

Peak detection in a 2D array

I detected the peaks using a local maximum filter. Here is the result on your first dataset of 4 paws: Peaks detection result

I also ran it on the second dataset of 9 paws and it worked as well.

Here is how you do it:

import numpy as np
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
import matplotlib.pyplot as pp

#for some reason I had to reshape. Numpy ignored the shape header.
paws_data = np.loadtxt("paws.txt").reshape(4,11,14)

#getting a list of images
paws = [p.squeeze() for p in np.vsplit(paws_data,4)]


def detect_peaks(image):
    """
    Takes an image and detect the peaks usingthe local maximum filter.
    Returns a boolean mask of the peaks (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """

    # define an 8-connected neighborhood
    neighborhood = generate_binary_structure(2,2)

    #apply the local maximum filter; all pixel of maximal value 
    #in their neighborhood are set to 1
    local_max = maximum_filter(image, footprint=neighborhood)==image
    #local_max is a mask that contains the peaks we are 
    #looking for, but also the background.
    #In order to isolate the peaks we must remove the background from the mask.

    #we create the mask of the background
    background = (image==0)

    #a little technicality: we must erode the background in order to 
    #successfully subtract it form local_max, otherwise a line will 
    #appear along the background border (artifact of the local maximum filter)
    eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

    #we obtain the final mask, containing only peaks, 
    #by removing the background from the local_max mask (xor operation)
    detected_peaks = local_max ^ eroded_background

    return detected_peaks


#applying the detection and plotting results
for i, paw in enumerate(paws):
    detected_peaks = detect_peaks(paw)
    pp.subplot(4,2,(2*i+1))
    pp.imshow(paw)
    pp.subplot(4,2,(2*i+2) )
    pp.imshow(detected_peaks)

pp.show()

All you need to do after is use scipy.ndimage.measurements.label on the mask to label all distinct objects. Then you'll be able to play with them individually.

Note that the method works well because the background is not noisy. If it were, you would detect a bunch of other unwanted peaks in the background. Another important factor is the size of the neighborhood. You will need to adjust it if the peak size changes (the should remain roughly proportional).

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

PHP preg_match - only allow alphanumeric strings and - _ characters

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

How to implement the factory method pattern in C++ correctly

I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:

there are cases when object construction is a task complex enough to justify its extraction to another class.

That class is in fact a Builder, rather than a Factory.

In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.

Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.

This also eliminates the issues related to return-by-value.

Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.

Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.

If you are after the "perfect" factory implementation, well, good luck.

Creating Unicode character from its number

Just cast your int to a char. You can convert that to a String using Character.toString():

String s = Character.toString((char)c);

EDIT:

Just remember that the escape sequences in Java source code (the \u bits) are in HEX, so if you're trying to reproduce an escape sequence, you'll need something like int c = 0x2202.

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

How to sum digits of an integer in java?

Java 8 Recursive Solution, If you dont want to use any streams.

UnaryOperator<Long> sumDigit = num -> num <= 0 ? 0 : num % 10 + this.sumDigit.apply(num/10);

How to use

Long sum = sumDigit.apply(123L);

Above solution will work for all positive number. If you want the sum of digits irrespective of positive or negative also then use the below solution.

UnaryOperator<Long> sumDigit = num -> num <= 0 ? 
         (num == 0 ? 0 : this.sumDigit.apply(-1 * num)) 
         : num % 10 + this.sumDigit.apply(num/10);

What's the difference between the atomic and nonatomic attributes?

The truth is that they use spin lock to implement atomic property. The code as below:

 static inline void reallySetProperty(id self, SEL _cmd, id newValue, 
      ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy) 
    {
        id oldValue;
        id *slot = (id*) ((char*)self + offset);

        if (copy) {
            newValue = [newValue copyWithZone:NULL];
        } else if (mutableCopy) {
            newValue = [newValue mutableCopyWithZone:NULL];
        } else {
            if (*slot == newValue) return;
            newValue = objc_retain(newValue);
        }

        if (!atomic) {
            oldValue = *slot;
            *slot = newValue;
        } else {
            spin_lock_t *slotlock = &PropertyLocks[GOODHASH(slot)];
            _spin_lock(slotlock);
            oldValue = *slot;
            *slot = newValue;        
            _spin_unlock(slotlock);
        }

        objc_release(oldValue);
    }

Git: add vs push vs commit

I find this image very meaningful :

enter image description here

(from : Oliver Steele -My Git Workflow (2008) )

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

What are best practices for multi-language database design?

I find this type of approach works for me:

Product     ProductDetail        Country
=========   ==================   =========
ProductId   ProductDetailId      CountryId
- etc -     ProductId            CountryName
            CountryId            Language
            ProductName          - etc -
            ProductDescription
            - etc -

The ProductDetail table holds all the translations (for product name, description etc..) in the languages you want to support. Depending on your app's requirements, you may wish to break the Country table down to use regional languages too.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

How to drop columns by name in a data frame

Here is another solution that may be helpful to others. The code below selects a small number of rows and columns from a large data set. The columns are selected as in one of juba's answers except that I use a paste function to select a set of columns with names that are numbered sequentially:

df = read.table(text = "

state county city  region  mmatrix  X1 X2 X3    A1     A2     A3      B1     B2     B3      C1      C2      C3

  1      1     1      1     111010   1  0  0     2     20    200       4      8     12      NA      NA      NA
  1      2     1      1     111010   1  0  0     4     NA    400       5      9     NA      NA      NA      NA
  1      1     2      1     111010   1  0  0     6     60     NA      NA     10     14      NA      NA      NA
  1      2     2      1     111010   1  0  0    NA     80    800       7     11     15      NA      NA      NA

  1      1     3      2     111010   0  1  0     1      2      1       2      2      2      10      20      30
  1      2     3      2     111010   0  1  0     2     NA      1       2      2     NA      40      50      NA
  1      1     4      2     111010   0  1  0     1      1     NA      NA      2      2      70      80      90
  1      2     4      2     111010   0  1  0    NA      2      1       2      2     10     100     110     120

  1      1     1      3     010010   0  0  1    10     20     10     200    200    200       1       2       3
  1      2     1      3     001000   0  0  1    20     NA     10     200    200    200       4       5       9
  1      1     2      3     101000   0  0  1    10     10     NA     200    200    200       7       8      NA
  1      2     2      3     011010   0  0  1    NA     20     10     200    200    200      10      11      12

", sep = "", header = TRUE, stringsAsFactors = FALSE)
df

df2 <- df[df$region == 2, names(df) %in% c(paste("C", seq_along(1:3), sep=''))]
df2

#    C1  C2  C3
# 5  10  20  30
# 6  40  50  NA
# 7  70  80  90
# 8 100 110 120

AngularJS : ng-click not working

Just add the function reference to the $scope in the controller:

for example if you want the function MyFunction to work in ng-click just add to the controller:

app.controller("MyController", ["$scope", function($scope) {
   $scope.MyFunction = MyFunction;
}]);

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

JavaScript alert not working in Android WebView

Check this link , and last comment , You have to use WebChromeClient for your purpose.

Any implementation of Ordered Set in Java?

Take a look at the Java standard API doc. Right next to LinkedHashMap, there is a LinkedHashSet. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).

There is also an interface SortedSet implemented by TreeSet and ConcurrentSkipListSet. Both allow iteration in the natural order of their elements or a Comparator, but not random access or insertion order.

For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

CLEAR SCREEN - Oracle SQL Developer shortcut?

Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.

Run script.

Alt+PgDn     -  puts you in Script Output panel.
Ctrl+Shift+D -  clears panel.
Alt+PgUp     -  puts you back in editor panel. 

Error: unable to verify the first certificate in nodejs

unable to verify the first certificate

The certificate chain is incomplete.

It means that the webserver you are connecting to is misconfigured and did not include the intermediate certificate in the certificate chain it sent to you.

Certificate chain

It most likely looks as follows:

  1. Server certificate - stores a certificate signed by intermediate.
  2. Intermediate certificate - stores a certificate signed by root.
  3. Root certificate - stores a self-signed certificate.

Intermediate certificate should be installed on the server, along with the server certificate.
Root certificates are embedded into the software applications, browsers and operating systems.

The application serving the certificate has to send the complete chain, this means the server certificate itself and all the intermediates. The root certificate is supposed to be known by the client.

Recreate the problem

Go to https://incomplete-chain.badssl.com using your browser.

It doesn't show any error (padlock in the address bar is green).
It's because browsers tend to complete the chain if it’s not sent from the server.

Now, connect to https://incomplete-chain.badssl.com using Node:

// index.js
const axios = require('axios');

axios.get('https://incomplete-chain.badssl.com')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Logs: "Error: unable to verify the first certificate".

Solution

You need to complete the certificate chain yourself.

To do that:

1: You need to get the missing intermediate certificate in .pem format, then

2a: extend Node’s built-in certificate store using NODE_EXTRA_CA_CERTS,

2b: or pass your own certificate bundle (intermediates and root) using ca option.

1. How do I get intermediate certificate?

Using openssl (comes with Git for Windows).

Save the remote server's certificate details:

openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com | tee logcertfile

We're looking for the issuer (the intermediate certificate is the issuer / signer of the server certificate):

openssl x509 -in logcertfile -noout -text | grep -i "issuer"

It should give you URI of the signing certificate. Download it:

curl --output intermediate.crt http://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt

Finally, convert it to .pem:

openssl x509 -inform DER -in intermediate.crt -out intermediate.pem -text

2a. NODE_EXTRA_CERTS

I'm using cross-env to set environment variables in package.json file:

"start": "cross-env NODE_EXTRA_CA_CERTS=\"C:\\Users\\USERNAME\\Desktop\\ssl-connect\\intermediate.pem\" node index.js"

2b. ca option

This option is going to overwrite the Node's built-in root CAs.

That's why we need to create our own root CA. Use ssl-root-cas.

Then, create a custom https agent configured with our certificate bundle (root and intermediate). Pass this agent to axios when making request.

// index.js
const axios = require('axios');
const path = require('path');
const https = require('https');
const rootCas = require('ssl-root-cas').create();

rootCas.addFile(path.resolve(__dirname, 'intermediate.pem'));
const httpsAgent = new https.Agent({ca: rootCas});

axios.get('https://incomplete-chain.badssl.com', { httpsAgent })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Instead of creating a custom https agent and passing it to axios, you can place the certifcates on the https global agent:

// Applies to ALL requests (whether using https directly or the request module)
https.globalAgent.options.ca = rootCas;

Resources:

  1. https://levelup.gitconnected.com/how-to-resolve-certificate-errors-in-nodejs-app-involving-ssl-calls-781ce48daded
  2. https://www.npmjs.com/package/ssl-root-cas
  3. https://github.com/nodejs/node/issues/16336
  4. https://www.namecheap.com/support/knowledgebase/article.aspx/9605/69/how-to-check-ca-chain-installation
  5. https://superuser.com/questions/97201/how-to-save-a-remote-server-ssl-certificate-locally-as-a-file/
  6. How to convert .crt to .pem

getting JRE system library unbound error in build path

The solution that work for me is the following:

  1. Select a project
  2. Select the project menu
  3. Select properties sub-menu
  4. In the window "properties for 'your project'", select Java Build Path tab
  5. Select libraries tab
  6. Select the troublesome JRE entry
  7. Click on edit button
  8. Select JRE entry
  9. Click on finish button

Selenium Webdriver: Entering text into text field

I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.

import org.openqa.selenium.Keys;

String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);

element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field

I hope it helps..

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

what is right way to do API call in react js?

Render function should be pure, it's mean that it only uses state and props to render, never try to modify the state in render, this usually causes ugly bugs and decreases performance significantly. It's also a good point if you separate data-fetching and render concerns in your React App. I recommend you read this article which explains this idea very well. https://medium.com/@learnreact/container-components-c0e67432e005#.sfydn87nm

Activate tabpage of TabControl

For Windows Smart device (compact frame work ) (MC75-Motorola devices)

     mytabControl.SelectedIndex = 1

Sorting arrays in javascript by object key value

Not spectacular different than the answers already given, but more generic is :

sortArrayOfObjects = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] - b[key];
    });
};

sortArrayOfObjects(yourArray, "distance");

Using current time in UTC as default value in PostgreSQL

Still another solution:

timezone('utc', now())

PHP json_encode json_decode UTF-8

This is an encoding issue. It looks like at some point, the data gets represented as ISO-8859-1.

Every part of your process needs to be UTF-8 encoded.

  • The database connection

  • The database tables

  • Your PHP file (if you are using special characters inside that file as shown in your example above)

  • The content-type headers that you output

How to expand 'select' option width after the user wants to select an option

Place it in a div and give it an id

<div id=myForm>

then create a really really simple css to go with it.

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

That's all you need.

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

In June 2018, in an effort to raise security and comply with modern standards, the insecure TLS 1.0 & 1.1 protocols will no longer be supported for SSL connections to Central. This should only affect users of Java 6 (and Java 7) that are also using https to access central, which by our metrics is less than .2% of users.

For more details and workarounds, see the blog and faq here: https://blog.sonatype.com/enhancing-ssl-security-and-http/2-support-for-central

How do I use a third-party DLL file in Visual Studio C++?

As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.

The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.

To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.

Troubleshooting "Illegal mix of collations" error in mysql

If the columns that you are having trouble with are "hashes", then consider the following...

If the "hash" is a binary string, you should really use BINARY(...) datatype.

If the "hash" is a hex string, you do not need utf8, and should avoid such because of character checks, etc. For example, MySQL's MD5(...) yields a fixed-length 32-byte hex string. SHA1(...) gives a 40-byte hex string. This could be stored into CHAR(32) CHARACTER SET ascii (or 40 for sha1).

Or, better yet, store UNHEX(MD5(...)) into BINARY(16). This cuts in half the size of the column. (It does, however, make it rather unprintable.) SELECT HEX(hash) ... if you want it readable.

Comparing two BINARY columns has no collation issues.

ASP.NET Identity reset password

In current release

Assuming you have handled the verification of the request to reset the forgotten password, use following code as a sample code steps.

ApplicationDbContext =new ApplicationDbContext()
String userId = "<YourLogicAssignsRequestedUserId>";
String newPassword = "<PasswordAsTypedByUser>";
ApplicationUser cUser = UserManager.FindById(userId);
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();            
store.SetPasswordHashAsync(cUser, hashedNewPassword);

In AspNet Nightly Build

The framework is updated to work with Token for handling requests like ForgetPassword. Once in release, simple code guidance is expected.

Update:

This update is just to provide more clear steps.

ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
String userId = User.Identity.GetUserId();//"<YourLogicAssignsRequestedUserId>";
String newPassword = "test@123"; //"<PasswordAsTypedByUser>";
String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);                    
ApplicationUser cUser = await store.FindByIdAsync(userId);
await store.SetPasswordHashAsync(cUser, hashedNewPassword);
await store.UpdateAsync(cUser);

Writing to a TextBox from another thread?

I would use BeginInvoke instead of Invoke as often as possible, unless you are really required to wait until your control has been updated (which in your example is not the case). BeginInvoke posts the delegate on the WinForms message queue and lets the calling code proceed immediately (in your case the for-loop in the SampleFunction). Invoke not only posts the delegate, but also waits until it has been completed.

So in the method AppendTextBox from your example you would replace Invoke with BeginInvoke like that:

public void AppendTextBox(string value)
{
    if (InvokeRequired)
    {
        this.BeginInvoke(new Action<string>(AppendTextBox), new object[] {value});
        return;
    }
    textBox1.Text += value;
}

Well and if you want to get even more fancy, there is also the SynchronizationContext class, which lets you basically do the same as Control.Invoke/Control.BeginInvoke, but with the advantage of not needing a WinForms control reference to be known. Here is a small tutorial on SynchronizationContext.

How to get element by innerText

To get the filter method from user1106925 working in <=IE11 if needed

You can replace the spread operator with:

[].slice.call(document.querySelectorAll("a"))

and the includes call with a.textContent.match("your search term")

which works pretty neatly:

[].slice.call(document.querySelectorAll("a"))
   .filter(a => a.textContent.match("your search term"))
   .forEach(a => console.log(a.textContent))

Multiline editing in Visual Studio Code

As of April 2018 (version 1.23) you can now also use the middle mouse button to multiline select / box select.

JSON.parse vs. eval()

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

How to determine the encoding of text?

Depending on your platform, I just opt to use the linux shell file command. This works for me since I am using it in a script that exclusively runs on one of our linux machines.

Obviously this isn't an ideal solution or answer, but it could be modified to fit your needs. In my case I just need to determine whether a file is UTF-8 or not.

import subprocess
file_cmd = ['file', 'test.txt']
p = subprocess.Popen(file_cmd, stdout=subprocess.PIPE)
cmd_output = p.stdout.readlines()
# x will begin with the file type output as is observed using 'file' command
x = cmd_output[0].split(": ")[1]
return x.startswith('UTF-8')

How to add text at the end of each line in Vim?

If you want to add ',' at end of the lines starting with 'key', use:

:%s/key.*$/&,

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

How much should a function trust another function

My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.

FromBody string parameter is giving null

Post the string with raw JSON, and do not forget the double quotation marks!

enter image description here

how to get bounding box for div element in jquery

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

How can I get an HTTP response body as a string?

Here's an example from another simple project I was working on using the httpclient library from Apache:

String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

just use EntityUtils to grab the response body as a String. very simple.

Quickest way to convert XML to JSON in Java

I found this the quick and easy way: Used: org.json.XML class from java-json.jar

if (statusCode == 200 && inputStream != null) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = bufferedReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}

Windows recursive grep command-line

I recommend a really great tool:

native unix utils:

Just unpack them and put that folder into your PATH environment variable and voila! :)

Works like a charm, and there are much more then just grep ;)

Java - Get a list of all Classes loaded in the JVM

There are multiple answers to this question, partly due to ambiguous question - the title is talking about classes loaded by the JVM, whereas the contents of the question says "may or may not be loaded by the JVM".

Assuming that OP needs classes that are loaded by the JVM by a given classloader, and only those classes - my need as well - there is a solution (elaborated here) that goes like this:

import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class CPTest {

    private static Iterator list(ClassLoader CL)
        throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
        Class CL_class = CL.getClass();
        while (CL_class != java.lang.ClassLoader.class) {
            CL_class = CL_class.getSuperclass();
        }
        java.lang.reflect.Field ClassLoader_classes_field = CL_class
                .getDeclaredField("classes");
        ClassLoader_classes_field.setAccessible(true);
        Vector classes = (Vector) ClassLoader_classes_field.get(CL);
        return classes.iterator();
    }

    public static void main(String args[]) throws Exception {
        ClassLoader myCL = Thread.currentThread().getContextClassLoader();
        while (myCL != null) {
            System.out.println("ClassLoader: " + myCL);
            for (Iterator iter = list(myCL); iter.hasNext();) {
                System.out.println("\t" + iter.next());
            }
            myCL = myCL.getParent();
        }
    }

}

One of the neat things about it is that you can choose an arbitrary classloader you want to check. It is however likely to break should internals of classloader class change, so it is to be used as one-off diagnostic tool.

How to grep for two words existing on the same line?

git grep

Here is the syntax using git grep combining multiple patterns using Boolean expressions:

git grep -e pattern1 --and -e pattern2 --and -e pattern3

The above command will print lines matching all the patterns at once.

If the files aren't under version control, add --no-index param.

Search files in the current directory that is not managed by Git.

Check man git-grep for help.

See also:

Connection failed: SQLState: '01000' SQL Server Error: 10061

I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.

Getting the name of a variable as a string

Whenever I have to do it, mostly while communicating json schema and constants with the frontend I define a class as follows

class Param:
    def __init__(self, name, value):
        self.name = name
        self.value = value

Then define the variable with name and value.

frame_folder_count = Param({'name':'frame_folder_count', 'value':10})

Now you can access the name and value using the object.

>>> frame_folder_count.name
'frame_folder_count'

How do I calculate the date in JavaScript three months prior to today?

_x000D_
_x000D_
var d = new Date();_x000D_
document.write(d + "<br/>");_x000D_
d.setMonth(d.getMonth() - 6);_x000D_
document.write(d);
_x000D_
_x000D_
_x000D_

How to preventDefault on anchor tags?

Lot of answers seem to be overkill. FOR ME , this works

 <a ng-href="#" ng-click="$event.preventDefault();vm.questionContainer($index)">{{question.Verbiage}}</a>

Set margins in a LinearLayout programmatically

Try this

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);

How to prevent form from being submitted?

Try this one...

HTML Code

<form class="submit">
    <input type="text" name="text1"/>
    <input type="text" name="text2"/>
    <input type="submit" name="Submit" value="submit"/>
</form>

jQuery Code

$(function(){
    $('.submit').on('submit', function(event){
        event.preventDefault();
        alert("Form Submission stopped.");
    });
});

or

$(function(){
    $('.submit').on('submit', function(event){
       event.preventDefault();
       event.stopPropagation();
       alert("Form Submission prevented / stopped.");
    });
});

Vertically aligning a checkbox

_x000D_
_x000D_
Add CSS:_x000D_
_x000D_
_x000D_
li {_x000D_
  display: table-row;_x000D_
 _x000D_
 }_x000D_
li div {_x000D_
   display: table-cell;_x000D_
   vertical-align: middle;_x000D_
_x000D_
  }_x000D_
.check{_x000D_
  width:20px;_x000D_
_x000D_
  }_x000D_
ul{_x000D_
   list-style: none;_x000D_
  }_x000D_
  
_x000D_
 <ul>_x000D_
       <li>_x000D_
_x000D_
           <div><label for="myid1">Subject1</label></div>_x000D_
            <div class="check"><input type="checkbox" value="1"name="subject" class="subject-list" id="myid1"></div>_x000D_
       </li>_x000D_
       <li>_x000D_
_x000D_
           <div><label for="myid2">Subject2</label></div>_x000D_
              <div class="check" ><input type="checkbox" value="2"  class="subject-list" name="subjct" id="myid2"></div>_x000D_
       </li>_x000D_
   </ul>
_x000D_
_x000D_
_x000D_

How to fix height of TR?

I had to do this to get the result that I wanted:

<td style="font-size:3px; float:left; height:5px; vertical-align:middle;" colspan="7"><div style="font-size:3px; height:5px; vertical-align:middle;"><b><hr></b></div></td>

It refused to work with only the cell or the div and needed both.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

Counting the occurrences / frequency of array elements

Solution using a map with O(n) time complexity.

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

const countOccurrences = (arr) => {
    const map = {};
    for ( var i = 0; i < arr.length; i++ ) {
        map[arr[i]] = ~~map[arr[i]] + 1;
    }
    return map;
}

Demo: http://jsfiddle.net/simevidas/bnACW/

Separators for Navigation

Add the separator to the li background and make sure the link doesn't expand to cover the separator, which means the separator won't be click-able.

pandas: best way to select all columns whose names start with X

Another option for the selection of the desired entries is to use map:

df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]

which gives you all the columns for rows that contain a 1:

   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
5     6.8         1             0        5          0

The row selection is done by

(df == 1).any(axis=1)

as in @ajcr's answer which gives you:

0     True
1     True
2     True
3    False
4    False
5     True
dtype: bool

meaning that row 3 and 4 do not contain a 1 and won't be selected.

The selection of the columns is done using Boolean indexing like this:

df.columns.map(lambda x: x.startswith('foo'))

In the example above this returns

array([False,  True,  True,  True,  True,  True, False], dtype=bool)

So, if a column does not start with foo, False is returned and the column is therefore not selected.

If you just want to return all rows that contain a 1 - as your desired output suggests - you can simply do

df.loc[(df == 1).any(axis=1)]

which returns

   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Get current category ID of the active page

I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.

I think the most direct and simple way to access the cat ID in a category page is:

$wp_query->query_vars['cat']

Cheers

Background color on input type=button :hover state sticks in IE

There might be a fix to <input type="button"> - but if there is, I don't know it.

Otherwise, a good option seems to be to replace it with a carefully styled a element.

Example: http://jsfiddle.net/Uka5v/

.button {
    background-color: #E3E1B8; 
    padding: 2px 4px;
    font: 13px sans-serif;
    text-decoration: none;
    border: 1px solid #000;
    border-color: #aaa #444 #444 #aaa;
    color: #000
}

Upsides include that the a element will style consistently between different (older) versions of Internet Explorer without any extra work, and I think my link looks nicer than that button :)

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

Can you change what a symlink points to after it is created?

AFAIK, no, you can't. You have to remove it and recreate it. Actually, you can overwrite a symlink and thus update the pathname referenced by it:

$ ln -s .bashrc test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 7 2009-09-23 17:12 test -> .bashrc
$ ln -s .profile test
ln: creating symbolic link `test': File exists
$ ln -s -f .profile test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 8 2009-09-23 17:12 test -> .profile

EDIT: As the OP pointed out in a comment, using the --force option will make ln perform a system call to unlink() before symlink(). Below, the output of strace on my linux box proving it:

$ strace -o /tmp/output.txt ln -s -f .bash_aliases test
$ grep -C3 ^unlink /tmp/output.txt 
lstat64("test", {st_mode=S_IFLNK|0777, st_size=7, ...}) = 0
stat64(".bash_aliases", {st_mode=S_IFREG|0644, st_size=2043, ...}) = 0
symlink(".bash_aliases", "test")        = -1 EEXIST (File exists)
unlink("test")                          = 0
symlink(".bash_aliases", "test")        = 0
close(0)                                = 0
close(1)                                = 0

So I guess the final answer is "no".

EDIT: The following is copied from Arto Bendiken's answer over on unix.stackexchange.com, circa 2016.

This can indeed be done atomically with rename(2), by first creating the new symlink under a temporary name and then cleanly overwriting the old symlink in one go. As the man page states:

If newpath refers to a symbolic link the link will be overwritten.

In the shell, you would do this with mv -T as follows:

$ mkdir a b
$ ln -s a z
$ ln -s b z.new
$ mv -T z.new z

You can strace that last command to make sure it is indeed using rename(2) under the hood:

$ strace mv -T z.new z
lstat64("z.new", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
lstat64("z", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
rename("z.new", "z")                    = 0

Note that in the above, both mv -T and strace are Linux-specific.

On FreeBSD, use mv -h alternately.

Editor's note: This is how Capistrano has done it for years now, ever since ~2.15. See this pull request.

Print series of prime numbers in python

How about this? Reading all the suggestions I used this:

prime=[2]+[num for num in xrange(3,m+1,2) if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1))]

Prime numbers up to 1000000

root@nfs:/pywork# time python prime.py

78498

real 0m6.600s

user 0m6.532s

sys 0m0.036s

Can I hide/show asp:Menu items based on role?

To find menu items in content page base on roles

 protected void Page_Load(object sender, EventArgs e)
{
   if (Session["AdminSuccess"] != null)
        {
           Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");

    //you must know the index of items to be removed first
    mainMenu.Items.RemoveAt(1);

    //or you try to hide menu and list items inside menu with css 
    // cssclass must be defined in style tag in .aspx page
    mainMenu.CssClass = ".hide";

        }   

}

<style type="text/css">
.hide
    {
        visibility: hidden;
     }
  </style>  

Remove a specific string from an array of string

Define "remove".

Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;

for (int i = 0; i < myStringArray.length(); i++)
{
    if (myStringArray[i].equals(stringToRemove))
    {
        myStringArray[i] = null;
        break;
    }
}

or

myStringArray[indexOfStringToRemove] = null;

If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>

myArrayList.remove(stringToRemove); 

or

myArrayList.remove(indexOfStringToRemove);

Edit in response to OP's edit to his question and comment below

String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));

How to send an object from one Android Activity to another using Intents?

I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.

Annotation: Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...

How to include multiple js files using jQuery $.getScript() method

I ran into a number of issues with multi script loading inculding one issue with (at least in Chrome) same domain hot loading of scripts not actually running after being successfully loaded by Ajax where as Cross Domain works perfectly fine! :(

The selected answer to original question does not work reliably.

After many many iterations here is my final answer to getScript(s) and loading asynchronously multiple scripts in a specific strict order with per script loaded callback option and overall callback on completion, Tested in jQuery 2.1+ and modern versions of Chrome, Firefox plus the forsaken Internet Explorer.

My test case was loading files for a THREE.JS webGL render then starting the render script when THREE global became available using an interval check passed to an anonymous function call to onComplete.

The Prototype function ( getScripts )

function getScripts( scripts, onScript, onComplete )
{
    this.async = true;
    this.cache = false;
    this.data = null;
    this.complete = function () { $.scriptHandler.loaded(); };
    this.scripts = scripts;
    this.onScript = onScript;
    this.onComplete = onComplete;
    this.total = scripts.length;
    this.progress = 0;
};

getScripts.prototype.fetch = function() {
    $.scriptHandler = this;
    var src = this.scripts[ this.progress ];
    console.log('%cFetching %s','color:#ffbc2e;', src);

    $.ajax({
        crossDomain:true,
        async:this.async,
        cache:this.cache,
        type:'GET',
        url: src,
        data:this.data,
        statusCode: {
            200: this.complete
        },
        dataType:'script'
    });
};

getScripts.prototype.loaded = function () {
    this.progress++;
    if( this.progress >= this.total ) {
        if(this.onComplete) this.onComplete();
    } else {
        this.fetch();
    };
    if(this.onScript) this.onScript();
};

How to use

var scripts = new getScripts(
    ['script1.js','script2.js','script.js'],
    function() {
        /* Optional - Executed each time a script has loaded (Use for Progress updates?) */
    },
    function () {
        /* Optional - Executed when the entire list of scripts has been loaded */
    }
);
scripts.fetch();

The function is as it is for I found using Deferred ( Deprecated now? ), When, Success & Complete in my trials to NOT be 100% reliable!?, Hence this function and use of statusCode for example.

You may want to add in error/fail handling behaviour if you wish.

Difference between @Mock and @InjectMocks

@Mock annotation mocks the concerned object.

@InjectMocks annotation allows to inject into the underlying object the different (and relevant) mocks created by @Mock.

Both are complementary.

How can I use Guzzle to send a POST request in JSON?

This worked for me (using Guzzle 6)

$client = new Client(); 
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>  
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

Trim leading and trailing spaces from a string in awk

remove leading and trailing white space in 2nd column

awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt

another way by one gsub:

awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile

Editing the git commit message in GitHub

GitHub's instructions for doing this:

  1. On the command line, navigate to the repository that contains the commit you want to amend.
  2. Type git commit --amend and press Enter.
  3. In your text editor, edit the commit message and save the commit.
  4. Use the git push --force example-branch command to force push over the old commit.

Source: https://help.github.com/articles/changing-a-commit-message/

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

How do I use Spring Boot to serve static content located in Dropbox folder?

To serve from file system

I added spring.resources.static-location=file:../frontend/build in application.properties

index.html is present in the build folder

Use can also add absolute path

spring.resources.static-location=file:/User/XYZ/Desktop/frontend/build

I think similarly you can try adding Dropbox folder path.

Declare and initialize a Dictionary in Typescript

If you want to ignore a property, mark it as optional by adding a question mark:

interface IPerson {
    firstName: string;
    lastName?: string;
}

Cannot use Server.MapPath

you can try using this

    System.Web.HttpContext.Current.Server.MapPath(path);

or use HostingEnvironment.MapPath

    System.Web.Hosting.HostingEnvironment.MapPath(path);

Draw a connecting line between two elements

jsPlumb is an option available that supports drag and drop, as seen by its numerous demos, including the Flowchart demo.

It is available in a free Community edition, and a paid Toolkit edition.

The Toolkit edition wraps the Community edition with a comprehensive data binding layer, as well as several UI widgets for building applications and integrations for popular libraries, and is commercially licensed.

How do I save and restore multiple variables in python?

You could use klepto, which provides persistent caching to memory, disk, or database.

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db['1'] = 1
>>> db['max'] = max
>>> squared = lambda x: x**2
>>> db['squared'] = squared
>>> def add(x,y):
...   return x+y
... 
>>> db['add'] = add
>>> class Foo(object):
...   y = 1
...   def bar(self, x):
...     return self.y + x
... 
>>> db['Foo'] = Foo
>>> f = Foo()
>>> db['f'] = f  
>>> db.dump()
>>> 

Then, after interpreter restart...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db
file_archive('foo.txt', {}, cached=True)
>>> db.load()
>>> db
file_archive('foo.txt', {'1': 1, 'add': <function add at 0x10610a0c8>, 'f': <__main__.Foo object at 0x10510ced0>, 'max': <built-in function max>, 'Foo': <class '__main__.Foo'>, 'squared': <function <lambda> at 0x10610a1b8>}, cached=True)
>>> db['add'](2,3)
5
>>> db['squared'](3)
9
>>> db['f'].bar(4)
5
>>> 

Get the code here: https://github.com/uqfoundation

map vs. hash_map in C++

Some of the key differences are in the complexity requirements.

  • A map requires O(log(N)) time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.

  • An unordered_map requires an 'average' time of O(1) for inserts and finds, but is allowed to have a worst-case time of O(N). This is because it's implemented using Hash Table data structure.

So, usually, unordered_map will be faster, but depending on the keys and the hash function you store, can become much worse.

Setting width and height

In my case, passing responsive: false under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.

CSS scrollbar style cross browser

jScrollPane is a good solution to cross browser scrollbars and degrades nicely.

Binding to static property

If you are using local resources you can refer to them as below:

<TextBlock Text="{Binding Source={x:Static prop:Resources.PerUnitOfMeasure}}" TextWrapping="Wrap" TextAlignment="Center"/>

Simple dynamic breadcrumb

Here is my solution based on Skeptic answer. It gets page title from WordPress DB, not from URL because there is a problem with latin characters (slug doesn't has a latin characters). You can also choose to display "home" item or not.

/**
 * Show Breadcrumbs
 * 
 * @param string|bool $home
 * @param string $class
 * @return string
 * 
 * Using: echo breadcrumbs();
 */
function breadcrumbs($home = 'Home', $class = 'items') {
    $breadcrumb  = '<ul class="'. $class .'">';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    if ($home) {
        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
    }

    $path = '';
    foreach ($breadcrumbs as $crumb) {
        $path .=  $crumb . '/';
        $page = get_page_by_path($path);

        if ($home && ($page->ID == get_option('page_on_front'))) {
            continue;
        }

        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
    }

    $breadcrumb .= '</ul>';
    return $breadcrumb;
}

Using:

<div class="breadcrumb">
    <div class="container">
        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
    </div>
</div>

The order of keys in dictionaries

From http://docs.python.org/tutorial/datastructures.html:

"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."

Is there any way to kill a Thread?

I'm way late to this game, but I've been wrestling with a similar question and the following appears to both resolve the issue perfectly for me AND lets me do some basic thread state checking and cleanup when the daemonized sub-thread exits:

import threading
import time
import atexit

def do_work():

  i = 0
  @atexit.register
  def goodbye():
    print ("'CLEANLY' kill sub-thread with value: %s [THREAD: %s]" %
           (i, threading.currentThread().ident))

  while True:
    print i
    i += 1
    time.sleep(1)

t = threading.Thread(target=do_work)
t.daemon = True
t.start()

def after_timeout():
  print "KILL MAIN THREAD: %s" % threading.currentThread().ident
  raise SystemExit

threading.Timer(2, after_timeout).start()

Yields:

0
1
KILL MAIN THREAD: 140013208254208
'CLEANLY' kill sub-thread with value: 2 [THREAD: 140013674317568]

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

jQuery event handlers always execute in order they were bound - any way around this?

You can do a custom namespace of events.

$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});

Then, when you need to trigger them you can choose the order.

$('span').trigger('click.doStuff1').trigger('click.doStuff2');

or

$('span').trigger('click.doStuff2').trigger('click.doStuff1');

Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do

$('span').trigger('click'); 

How to update gradle in android studio?

Go to File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path

Now, set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties files field distributionUrl like this

distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

How to change language settings in R

The only thing that worked for me was uninstalling R entirely (make sure to remove it from the Programs files as well), and install it, but unselect Message Translations during the installation process. When I installed R, and subsequently RCmdr, it finally came up in English.

Calling Python in PHP

You can run a python script via php, and outputs on browser.

Basically you have to call the python script this way:

$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
 usleep(100000);
}
pclose($pid);

Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.

For full codes working, visit How to execute python script from php and show output on browser

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

Did the following for a spring application running static, rest and websocket content.

The Apache is used as Proxy and SSL Endpoint for the following URIs:

  • /app → static content
  • /api → REST API
  • /api/ws → websocket

Apache configuration

<VirtualHost *:80>
    ServerName xxx.xxx.xxx    

    ProxyRequests Off
    ProxyVia Off
    ProxyPreserveHost On

    <Proxy *>
         Require all granted
    </Proxy>

    RewriteEngine On

    # websocket 
    RewriteCond %{HTTP:Upgrade}         =websocket                      [NC]
    RewriteRule ^/api/ws/(.*)           ws://localhost:8080/api/ws/$1   [P,L]

    # rest
    ProxyPass /api http://localhost:8080/api
    ProxyPassReverse /api http://localhost:8080/api

    # static content    
    ProxyPass /app http://localhost:8080/app
    ProxyPassReverse /app http://localhost:8080/app 
</VirtualHost>

I use the same vHost config for the SSL configuration, no need to change anything proxy related.

Spring configuration

server.use-forward-headers: true

Byte[] to ASCII

As an alternative to reading a data from a stream to a byte array, you could let the framework handle everything and just use a StreamReader set up with an ASCII encoding to read in the string. That way you don't need to worry about getting the appropriate buffer size or larger data sizes.

using (var reader = new StreamReader(stream, Encoding.ASCII))
{
    string theString = reader.ReadToEnd();
    // do something with theString
}

How to list all the files in android phone by using adb shell?

I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try

adb shell ls -R /

You probably need the root permission though.

Edit: As other answers suggest, use ls with grep like this:

adb shell ls -Ral yourDirectory | grep -i yourString

eg.

adb shell ls -Ral / | grep -i myfile

-i is for ignore-case. and / is the root directory.

How do I ZIP a file in C#, using no 3rd-party APIs?

How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?

If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.

using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
    zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}

You need to add references to:

  • System.IO.Compression
  • System.IO.Compression.FileSystem

For .NET Core targeting net46, you need to add dependencies for

  • System.IO.Compression
  • System.IO.Compression.ZipFile

Example project.json:

"dependencies": {
  "System.IO.Compression": "4.1.0",
  "System.IO.Compression.ZipFile": "4.0.1"
},

"frameworks": {
  "net46": {}
}

For .NET Core 2.0, just adding a simple using statement is all that is needed:

  • using System.IO.Compression;

How can I stage and commit all files, including newly added files, using a single command?

This command will add and commit all the modified files, but not newly created files:

git commit -am  "<commit message>"

From man git-commit:

-a, --all
    Tell the command to automatically stage files that have been modified
    and deleted, but new files you have not told Git about are not
    affected.

How to set a reminder in Android?

You can use AlarmManager in coop with notification mechanism Something like this:

Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
    am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}

It starts alarm.

public class ReminderBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(...)
                .setContentTitle(..)
                .setContentText(..);
        Intent intentToFire = new Intent(context, Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
    }
}

How to check permissions of a specific directory?

You can also use the stat command if you want detailed information on a file/directory. (I precise this as you say you are learning ^^)

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

Java: parse int value from a char

Try the following:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

if u subtract by char '0', the ASCII value needs not to be known.

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

How can I obfuscate (protect) JavaScript?

I am using Closure-Compiler utility for the java-script obfuscation. It minifies the code and has more options for obfuscation. This utility is available at Google code at below URL:
Closure Tools

But now a days I am hearing much of UglifyJS. You can find various comparison between Closure Compiler and UglifyJS in which Uglify seems to be a winner.
UglifyJS: A Fast New JavaScript Compressor For Node.js That’s On Par With Closure

Soon I would give chance to UglifyJS.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I had to set

C:\ProgramData\MySQL\MySQL Server 8.0/my.ini  secure-file-priv=""

When I commented line with secure-file-priv, secure-file-priv was null and I couldn't download data.

Android, getting resource ID from string?

In MonoDroid / Xamarin.Android you can do:

 var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);

But since GetIdentifier it's not recommended in Android - you can use Reflection like this:

 var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);

where I suggest to put a try/catch or verify the strings you are passing.

set up device for development (???????????? no permissions)

There are a lot of bad answers posted to this question ranging from insisting on running adb as root (which should not be touted as the only or even recommended solution) to solving completely unrelated issues.

Here is the single shortest and most universal recipe for taking care of permissions for all adb and fastboot devices at once:

echo 'ACTION=="add", SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:ff420?:*", MODE="0666"' | sudo tee /etc/udev/rules.d/99-android.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --verbose --action=add --subsystem-match=usb

Or you could use slightly longer version I posted to this gist.

As for the specific thing that OP did wrong in his question - it was not reloading the udev rules after editing the .rules file.

Also OP did not tell which Android build (aka ROM) he had on his phone. The idVendor value is set in software and therefore it depends on the ROM. So the value of 04E8 he used in his original rule would have worked only for devices with Samsung stock ROMs. But this is not a problem for this udev rule - it matches all devices with adb or fastboot interfaces regardless of their VendorID.

What is 0x10 in decimal?

Notice that '10' is the representation of the base in that base:

10 is 2(decimal) in base-2

10 is 3(decimal) in base-3

...

10 is 10(decimal) in base-10

...

10 is 16(decimal) in base-16 (hexadecimal)

...

10 is 1024(decimal) in base-1024

...and so on

Is it possible to overwrite a function in PHP

Monkey patch in namespace php >= 5.3

A less evasive method than modifying the interpreter is the monkey patch.

Monkey patching is the art of replacing the actual implementation with a similar "patch" of your own.

Ninja skills

Before you can monkey patch like a PHP Ninja we first have to understand PHPs namespaces.

Since PHP 5.3 we got introduced to namespaces which you might at first glance denote to be equivalent to something like java packages perhaps, but it's not quite the same. Namespaces, in PHP, is a way to encapsulate scope by creating a hierarchy of focus, especially for functions and constants. As this topic, fallback to global functions, aims to explain.

If you don't provide a namespace when calling a function, PHP first looks in the current namespace then moves down the hierarchy until it finds the first function declared within that prefixed namespace and executes that. For our example if you are calling print_r(); from namespace My\Awesome\Namespace; What PHP does is to first look for a function called My\Awesome\Namespace\print_r(); then My\Awesome\print_r(); then My\print_r(); until it finds the PHP built in function in the global namespace \print_r();.

You will not be able to define a function print_r($object) {} in the global namespace because this will cause a name collision since a function with that name already exists.

Expect a fatal error to the likes of:

Fatal error: Cannot redeclare print_r()

But nothing stops you, however, from doing just that within the scope of a namespace.

Patching the monkey

Say you have a script using several print_r(); calls.

Example:

<?php
     print_r($some_object);
     // do some stuff
     print_r($another_object);
     // do some other stuff
     print_r($data_object);
     // do more stuff
     print_r($debug_object);

But you later change your mind and you want the output wrapped in <pre></pre> tags instead. Ever happened to you?

Before you go and change every call to print_r(); consider monkey patching instead.

Example:

<?php
    namespace MyNamespace {
        function print_r($object) 
        {
            echo "<pre>", \print_r($object, true), "</pre>"; 
        }

        print_r($some_object);
        // do some stuff
        print_r($another_object);
        // do some other stuff
        print_r($data_object);
        // do more stuff
        print_r($debug_object);
    }

Your script will now be using MyNamespace\print_r(); instead of the global \print_r();

Works great for mocking unit tests.

nJoy!

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

How do I float a div to the center?

There is no float: center; in css. Use margin: 0 auto; instead. So like this:

.mydivclass {
    margin: 0 auto;
 }

Clicking URLs opens default browser

in some cases you might need an override of onLoadResource if you get a redirect which doesn't trigger the url loading method. in this case i tried the following:

@Override
public void onLoadResource(WebView view, String url)
{
    if (url.equals("http://redirectexample.com"))
    {
        //do your own thing here
    }
    else
    {
        super.onLoadResource(view, url);
    }           
}

Calling constructors in c++ without new

Ideally, a compiler would optimize the second, but it's not required. The first is the best way. However, it's pretty critical to understand the distinction between stack and heap in C++, sine you must manage your own heap memory.

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

Add space between cells (td) using css

cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.

How to execute a Windows command on a remote PC?

If you are in a domain environment, you can also use:

winrs -r:PCNAME cmd

This will open a remote command shell.

Setting up Eclipse with JRE Path

Add this to eclipse.ini:

-vm
your_java_path\bin\javaw.exe

...but be aware that you must add these lines before -vmargs

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

How to set tint for an image view programmatically in android?

In case you want to set selector to your tint:

ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

CSS: Hover one element, effect for multiple elements?

I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:

<html>
<head>
<style>
  div.both:hover .image { border: 1px solid blue }
  div.both:hover .layer { border: 1px solid blue }
</style>
</head>

<body>
<div class="section">

<div class="both">
  <div class="image"><img src="myImage.jpg" /></div>
  <div class="layer">Lorem Ipsum</div>
</div>

</div>
</body>
</html>

How to take off line numbers in Vi?

Easily Display Line number:

set number flag (to show line number type)

:set nu or :set number

to unset the number flag (hide the line number type)

:set nu!

If you need number every time you start vi/vim, append following line to your ~/.vimrc file:

set number

Open a file at particular location/line number

$ vi +linenumber file.rb
$ vi +300 initlib.rb 

Adding options to select with javascript

The most concise and intuitive way would be:

_x000D_
_x000D_
var selectElement = document.getElementById('ageselect');_x000D_
_x000D_
for (var age = 12; age <= 100; age++) {_x000D_
  selectElement.add(new Option(age));_x000D_
}
_x000D_
Your age: <select id="ageselect"><option value="">Please select</option></select>
_x000D_
_x000D_
_x000D_

You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect?Element?.add(item[, before]);
new Option(text, value, defaultSelected, selected);

How do I print debug messages in the Google Chrome JavaScript Console?

Improving on Andru's idea, you can write a script which creates console functions if they don't exist:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

Then, use any of the following:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

youtube: link to display HD video by default

Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.

Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080

What you get as a result is the standalone 1080p video but not in the Tube environment.

Get all Attributes from a HTML element with Javascript/jQuery

In javascript:

var attributes;
var spans = document.getElementsByTagName("span");
for(var s in spans){
  if (spans[s].getAttribute('name') === 'test') {
     attributes = spans[s].attributes;
     break;
  }
}

To access the attributes names and values:

attributes[0].nodeName
attributes[0].nodeValue

Pseudo-terminal will not be allocated because stdin is not a terminal

Try ssh -t -t(or ssh -tt for short) to force pseudo-tty allocation even if stdin isn't a terminal.

See also: Terminating SSH session executed by bash script

From ssh manpage:

-T      Disable pseudo-tty allocation.

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary 
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty
        allocation, even if ssh has no local tty.

How to use a table type in a SELECT FROM statement?

In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

create type exch_row as object (
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);

create type exch_tbl as table of exch_row;

And then you can use it in SQL with TABLE operator, for example:

declare
   l_row     exch_row;
   exch_rt   exch_tbl;
begin
   l_row := exch_row('PLN', 100, 100);
   exch_rt  := exch_tbl(l_row);

   for r in (select i.*
               from item i, TABLE(exch_rt) rt
              where i.currency = rt.currency_cd) loop
      -- your code here
   end loop;
end;
/

filename and line number of Python script

Filename:

__file__
# or
sys.argv[0]

Line:

inspect.currentframe().f_lineno

(not inspect.currentframe().f_back.f_lineno as mentioned above)

What is the maximum length of a URL in different browsers?

WWW FAQs: What is the maximum length of a URL? has its own answer based on empirical testing and research. The short answer is that going over 2048 characters makes Internet Explorer unhappy and thus this is the limit you should use. See the page for a long answer.

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

Deleting queues in RabbitMQ

A short summary for quick queue deletion with all default values from the host that is running RMQ server:

curl -O http://localhost:15672/cli/rabbitmqadmin
chmod u+x rabbitmqadmin
./rabbitmqadmin delete queue name=myQueueName

To delete all queues matching a pattern in a given vhost (e.g. containing 'amq.gen' in the root vhost):

rabbitmqctl -p / list_queues | grep 'amq.gen' | cut -f1 -d$'\t' | xargs -I % ./rabbitmqadmin -V / delete queue name=%

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

How to download the latest artifact from Artifactory repository?

In case you need to download an artifact in a Dockerfile, instead of using wget or curl or the likes you can simply use the 'ADD' directive:

ADD ${ARTIFACT_URL} /opt/app/app.jar

Of course, the tricky part is determining the ARTIFACT_URL, but there's enough about that in all the other answers.

However, Docker best practises strongly discourage using ADD for this purpose and recommend using wget or curl.

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()

That said, everybody seems to come to this page for the more general answer to your question:

Selecting a random row in SQL

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Select a random row with sqlite:

SELECT column FROM table 
ORDER BY RANDOM() LIMIT 1

How to create duplicate table with new name in SQL Server 2008

Here, I will show you 2 different implementation:

First:

If you just need to create a duplicate table then just run the command:

SELECT top 0 * INTO [dbo].[DuplicateTable]
FROM [dbo].[MainTable]

Of course, it doesn't work completely. constraints don't get copied, nor do primary keys, or default values. The command only creates a new table with the same column structure and if you want to insert data into the new table.

Second (recommended):

But If you want to duplicate the table with all its constraints & keys follows this below steps:

  1. Open the database in SQL Management Studio.
  2. Right-click on the table that you want to duplicate.
  3. Select Script Table as -> Create to -> New Query Editor Window. This will generate a script to recreate the table in a new query window.
  4. Change the table name and relative keys & constraints in the script.
  5. Execute the script.

How can I install packages using pip according to the requirements.txt file from a local directory?

Use:

pip install -r requirements.txt

For further details, please check the help option:

pip install --help

We can find the option '-r' -

-r, --requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options (this is the help option on the pip install command):

Enter image description here

Also the above is the complete set of options. Please use pip install --help for the complete list of options.

Rollback one specific migration in Laravel

As stated in the Laravel manual, you may roll back specific number of migrations using the --step option

php artisan migrate:rollback --step=5

PostgreSQL error 'Could not connect to server: No such file or directory'

I don't really know Mac or Homebrew, but I know PostgreSQL very well.

You want to figure out where the logs are from PostgreSQL trying to start and what the socket directory is for PostgreSQL. By default when you build PG, the socket directory is /tmp/. If you didn't change that when you built PG and then you started PG, you should be able to see a socket file in /tmp if you do: ls -al /tmp

The socket file starts with a ".", so you won't see it with the '-a' to ls.

If you don't see a socket there, and you don't see anything from ps awux | grep postgres, then PG is probably not running, or maybe it is and it's the OSX-installed one. What might be happening is that you might be getting a conflict on listening on port 5432 on localhost- use netstat -anp to see what, if anything, is listening on 5432. If a Mac OSX PG is already listening on that port then that might be the problem.

Hope that helps. I have heard that homebrew can make things a bit ugly and a lot of people I've talked to encourage using a VM instead.

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

Mobile Redirect using htaccess

First, go to the following URL and download the mobile_detect.php file:

http://code.google.com/p/php-mobile-detect/

Insert the following code on your index or home page:

<?php
@include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
{
$detect = "false";
}
elseif ($detect->isMobile())
{
header("Location:http://www.yourmobiledirectory.com");
}
?>

Real differences between "java -server" and "java -client"?

From Goetz - Java Concurrency in Practice:

  1. Debugging tip: For server applications, be sure to always specify the -server JVM command line switch when invoking the JVM, even for development and testing. The server JVM performs more optimization than the client JVM, such as hoisting variables out of a loop that are not modified in the loop; code that might appear to work in the development environment (client JVM) can break in the deployment environment (server JVM). For example, had we “forgotten” to declare the variable asleep as volatile in Listing 3.4, the server JVM could hoist the test out of the loop (turning it into an infinite loop), but the client JVM would not. An infinite loop that shows up in development is far less costly than one that only shows up in production.

Listing 3.4. Counting sheep.

volatile boolean asleep; ... while (!asleep) countSomeSheep();

My emphasis. YMMV

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

Count number of rows matching a criteria

Call nrow passing as argument the name of the dataset:

nrow(dataset)

No newline after div?

Have you considered using span instead of div? It is the in-line version of div.

How to delete a certain row from mysql table with same column values?

There are already answers for Deleting row by LIMIT. Ideally you should have primary key in your table. But if there is not.

I will give other ways:

  1. By creating Unique index

I see id_users and id_product should be unique in your example.

ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)

These will delete duplicate rows with same data.

But if you still get an error, even if you use IGNORE clause, try this:

ALTER TABLE orders ENGINE MyISAM;
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
ALTER TABLE orders ENGINE InnoDB; 
  1. By creating table again

If there are multiple rows who have duplicate values, then you can also recreate table

RENAME TABLE `orders` TO `orders2`;

CREATE TABLE `orders` 
SELECT * FROM `orders2` GROUP BY id_users, id_product;

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

How do I make a placeholder for a 'select' box?

I wanted the SELECT to be grey until selected so for this piece of HTML:

<select>
  <option value="" disabled selected>Select your option</option>
  <option value="hurr">Durr</option>
</select>

I've added these CSS definitions:

select { color: grey; }
select:valid { color: black; }

It works as expected in Chrome / Safari and maybe also in other browsers, but I haven't checked.

Receiving "Attempted import error:" in react app

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e

export const addPost = (id) =>{
  ...
 }

Note while importing you need to wrap it in curly braces i.e. import {addPost} from '../URL';

But when using export default i.e

const addPost = (id) =>{
  ...
 }

export default addPost,

Then you can import without curly braces i.e. import addPost from '../url';

export default addPost

I hope this helps anyone who got confused as me.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

When to use Hadoop, HBase, Hive and Pig?

Short answer to this question is -

Hadoop - Is Framework which facilitates distributed file system and programming model which allow us to store humongous sized data and process data in distributed fashion very efficiently and with very less processing time compare to traditional approaches.

(HDFS - Hadoop Distributed File system) (Map Reduce - Programming Model for distributed processing)

Hive - Is query language which allows to read/write data from Hadoop distributed file system in a very popular SQL like fashion. This made life easier for many non-programming background people as they don't have to write Map-Reduce program anymore except for very complex scenarios where Hive is not supported.

Hbase - Is Columnar NoSQL Database. Underlying storage layer for Hbase is again HDFS. Most important use case for this database is to be able to store billion's of rows with million's of columns. Low latency feature of Hbase helps faster and random access of record over distributed data, is very important feature to make it useful for complex projects like Recommender Engines. Also it's record level versioning capability allow user to store transactional data very efficiently (this solves the problem of updating records we have with HDFS and Hive)

Hope this is helpful to quickly understand the above 3 features.

Facebook share button and custom text

This is the current solution (Dec 2014) and works quite well. It features

  • open a popup window
  • self-contained snippet, doesn't require anything else
  • works with or without JS. If JS is disabled, the share window still opens, albeit not as a small popup.

<a onclick="return !window.open(this.href, 'Share on Facebook', 'width=640, height=536')" href="https://www.facebook.com/sharer/sharer.php?u=href=$url&display=popup&ref=plugin" target="_window"><img src='/_img/icons/facebook.png' /></a>

$url var should be defined as the URL to share.

how to run mysql in ubuntu through terminal

You seem to just have begun using mysql.

Simple answer: for now use

mysql -u root -p password

Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.

Android ADB doesn't see device

For Windows 8 64 bit with a Nexus 10 device, this worked for me:

https://github.com/koush/UniversalAdbDriver

It has a link at the bottom to this:

http://download.clockworkmod.com/test/UniversalAdbDriverSetup.msi

Can we overload the main method in Java?

YES, you can overload main()

But to be clear -- although you can overload main, only the version with the standard signature will be executable as an application from the command line. e.g

public static void main(String a,String... args){
// some code
}
2)public static void main(String[] args){//JVM will call this method to start 
// some code 
}

How to Apply Corner Radius to LinearLayout

You can create an XML file in the drawable folder. Call it, for example, shape.xml

In shape.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"   >

    <solid
        android:color="#888888" >
    </solid>

    <stroke
        android:width="2dp"
        android:color="#C4CDE0" >
    </stroke>

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <corners
        android:radius="11dp"   >
    </corners>

</shape>

The <corner> tag is for your specific question.

Make changes as required.

And in your whatever_layout_name.xml:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/shape"    >
</LinearLayout>

This is what I usually do in my apps. Hope this helps....

How can I create directory tree in C++/Linux?

Here is my example of code (it works for both Windows and Linux):

#include <iostream>
#include <string>
#include <sys/stat.h> // stat
#include <errno.h>    // errno, ENOENT, EEXIST
#if defined(_WIN32)
#include <direct.h>   // _mkdir
#endif

bool isDirExist(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    if (_stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & _S_IFDIR) != 0;
#else 
    struct stat info;
    if (stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & S_IFDIR) != 0;
#endif
}

bool makePath(const std::string& path)
{
#if defined(_WIN32)
    int ret = _mkdir(path.c_str());
#else
    mode_t mode = 0755;
    int ret = mkdir(path.c_str(), mode);
#endif
    if (ret == 0)
        return true;

    switch (errno)
    {
    case ENOENT:
        // parent didn't exist, try to create it
        {
            int pos = path.find_last_of('/');
            if (pos == std::string::npos)
#if defined(_WIN32)
                pos = path.find_last_of('\\');
            if (pos == std::string::npos)
#endif
                return false;
            if (!makePath( path.substr(0, pos) ))
                return false;
        }
        // now, try to create again
#if defined(_WIN32)
        return 0 == _mkdir(path.c_str());
#else 
        return 0 == mkdir(path.c_str(), mode);
#endif

    case EEXIST:
        // done!
        return isDirExist(path);

    default:
        return false;
    }
}

int main(int argc, char* ARGV[])
{
    for (int i=1; i<argc; i++)
    {
        std::cout << "creating " << ARGV[i] << " ... " << (makePath(ARGV[i]) ? "OK" : "failed") << std::endl;
    }
    return 0;
}

Usage:

$ makePath 1/2 folderA/folderB/folderC
creating 1/2 ... OK
creating folderA/folderB/folderC ... OK

Managing large binary files with Git

git clone --filter from Git 2.19 + shallow clones

This new option might eventually become the final solution to the binary file problem, if the Git and GitHub devs and make it user friendly enough (which they arguably still haven't achieved for submodules for example).

It allows to actually only fetch files and directories that you want for the server, and was introduced together with a remote protocol extension.

With this, we could first do a shallow clone, and then automate which blobs to fetch with the build system for each type of build.

There is even already a --filter=blob:limit<size> which allows limiting the maximum blob size to fetch.

I have provided a minimal detailed example of how the feature looks like at: How do I clone a subdirectory only of a Git repository?

SQL SELECT WHERE field contains words

This should ideally be done with the help of sql server full text search if using. However, if you can't get that working on your DB for some reason, here is a performance intensive solution :-

-- table to search in
CREATE TABLE dbo.myTable
    (
    myTableId int NOT NULL IDENTITY (1, 1),
    code varchar(200) NOT NULL, 
    description varchar(200) NOT NULL -- this column contains the values we are going to search in 
    )  ON [PRIMARY]
GO

-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
  id nvarchar(1000)
)
AS
BEGIN
  DECLARE @String nvarchar(100);

  WHILE LEN(@StringInput) > 0
  BEGIN
    SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
    LEN(@StringInput)));
    SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
    (
    @Delimiter, @StringInput
    ),
    0
    ), LEN
    (
    @StringInput)
    )
    + 1, LEN(@StringInput));

    INSERT INTO @OutputTable (id)
      VALUES (@String);
  END;

  RETURN;
END;
GO

-- this is the search script which can be optionally converted to a stored procedure /function


declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain

if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
 select 1 as Priority ,myTableid, code, Description from myTable order by Description 
 return;
end

declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)

insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')

insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
--  id
-------------
-- infection
-- upper
-- acute
-- genito

delete s from @splitTable s join @nonWordTable n  on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable);  -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);

with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search  -- exact matches have highest priority
union                                      
select myTableid, @highestPriority-1 as Priority from myTable where Description like  @search + '%'  -- then with something at the end
union                                      
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union                                      
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
                     -- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description)  from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
                                                                              -- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
 select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
                     -- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex 
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
                              -- their sequence in the field value is taken into account for higher priority
    select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
    from wordIndexRatings w left join 
    (
     select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
     from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
     group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
    ) 
    sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select  w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId =  w2.myTableId 
where w1.word <> w2.word group by w1.myTableid 
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority  from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable  on m.myTableId = myTable.myTableId 
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging

Custom circle button

here is how you can perform simply, make a drawable resource file in drawable.xml. Say round_button.xml and then paste the following code.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
       <shape
           android:shape="oval">

           <solid
               android:color="@color/button_start_gradient_color"/>
       </shape>
    </item>
    <item
        android:drawable="@drawable/microphone"/>
</layer-list>

Note:- use your own color and drawable resource as i have used @drawable/microphone

Following is the result [1]: https://i.stack.imgur.com/QyhdJ.png