Programs & Examples On #Image editor

How to check if a String contains any of some strings

You can use Regular Expressions

if(System.Text.RegularExpressions.IsMatch("a|b|c"))

TS1086: An accessor cannot be declared in ambient context

I think that your problem was emerged from typescript and module version mismatch.This issue is very similar to your question and answers are very satisfying.

Get record counts for all tables in MySQL database

The following query produces a(nother) query that will get the value of count(*) for every table, from every schema, listed in information_schema.tables. The entire result of the query shown here - all rows taken together - comprise a valid SQL statement ending in a semicolon - no dangling 'union'. The dangling union is avoided by use of a union in the query below.

select concat('select "', table_schema, '.', table_name, '" as `schema.table`,
                          count(*)
                 from ', table_schema, '.', table_name, ' union ') as 'Query Row'
  from information_schema.tables
 union
 select '(select null, null limit 0);';

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height
        print(keyboardheight)
    }
}

load csv into 2D matrix with numpy for plotting

Pure numpy

numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)

Check out the loadtxt documentation.

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

Added Hint:

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.

Event on a disabled input

I find another solution:

<input type="text" class="disabled" name="test" value="test" />

Class "disabled" immitate disabled element by opacity:

<style type="text/css">
    input.disabled {
        opacity: 0.5;
    }
</style>

And then cancel the event if element is disabled and remove class:

$(document).on('click','input.disabled',function(event) {
    event.preventDefault();
    $(this).removeClass('disabled');
});

Codeigniter displays a blank page instead of error messages

Are you using the @ symbol anywhere?

If you have something like:

@include('page_with_error.php');

You will get a blank page.

Check if an element is present in a Bash array

As bash does not have a built-in value in array operator and the =~ operator or the [[ "${array[@]" == *"${item}"* ]] notation keep confusing me, I usually combine grep with a here-string:

colors=('black' 'blue' 'light green')
if grep -q 'black' <<< "${colors[@]}"
then
    echo 'match'
fi

Beware however that this suffers from the same false positives issue as many of the other answers that occurs when the item to search for is fully contained, but is not equal to another item:

if grep -q 'green' <<< "${colors[@]}"
then
    echo 'should not match, but does'
fi

If that is an issue for your use case, you probably won't get around looping over the array:

for color in "${colors[@]}"
do
    if [ "${color}" = 'green' ]
    then
        echo "should not match and won't"
        break
    fi
done

for color in "${colors[@]}"
do
    if [ "${color}" = 'light green' ]
    then
        echo 'match'
        break
    fi
done

How to analyse the heap dump using jmap in java

MAT, jprofiler,jhat are possible options. since jhat comes with jdk, you can easily launch it to do some basic analysis. check this out

Background color for Tk in Python

root.configure(background='black')

or more generally

<widget>.configure(background='black')

Replace "\\" with "\" in a string in C#

You can simply do a replace in your string like

Str.Replace(@"\\",@"\");

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

What is the difference between visibility:hidden and display:none?

They're not synonyms - display: none removes the element from the flow of the page, and rest of the page flows as if it weren't there.

visibility: hidden hides the element from view but not the page flow, leaving space for it on the page.

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

public static const in TypeScript

Here's what's this TS snippet compiled into (via TS Playground):

define(["require", "exports"], function(require, exports) {
    var Library = (function () {
        function Library() {
        }
        Library.BOOK_SHELF_NONE = "None";
        Library.BOOK_SHELF_FULL = "Full";
        return Library;
    })();
    exports.Library = Library;
});

As you see, both properties defined as public static are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.

Convert char array to single int?

I use :

int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}

How to declare a type as nullable in TypeScript?

type MyProps = {
  workoutType: string | null;
};

How to stop the Timer in android?

     CountDownTimer waitTimer;
     waitTimer = new CountDownTimer(60000, 300) {

       public void onTick(long millisUntilFinished) {
          //called every 300 milliseconds, which could be used to
          //send messages or some other action
       }

       public void onFinish() {
          //After 60000 milliseconds (60 sec) finish current 
          //if you would like to execute something when time finishes          
       }
     }.start();

to stop the timer early:

     if(waitTimer != null) {
         waitTimer.cancel();
         waitTimer = null;
     }

Get Locale Short Date Format using javascript

new Date(YOUR_DATE_STRING).toLocaleDateString(navigator.language)

~ combination of answers of above

How do I find the index of a character within a string in C?

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I got same error. This is how it worked for me:

  • cleaned the project under currently installed gcc
  • recompiled it

Worked perfectly!

How to submit an HTML form on loading the page?

Do this :

$(document).ready(function(){
     $("#frm1").submit();
});

No 'Access-Control-Allow-Origin' header is present on the requested resource error

For development you can use https://cors-anywhere.herokuapp.com , for production is better to set up your own proxy

_x000D_
_x000D_
async function read() {_x000D_
   let r= await (await fetch('https://cors-anywhere.herokuapp.com/http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi')).json();_x000D_
   console.log(r);_x000D_
}_x000D_
_x000D_
read();
_x000D_
_x000D_
_x000D_

What Java FTP client library should I use?

You have also this 2006 article which lists different options for FTP clients.

commons-net is good, but FTP-GO can give you some of the more advanced features you are looking for.

kagi Ftp-Go

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

DECLARE @EndTime AS DATETIME, @StartTime AS DATETIME

SELECT @StartTime = '2013-03-08 08:00:00', @EndTime = '2013-03-08 08:30:00'

SELECT CAST(@EndTime - @StartTime AS TIME)

Result: 00:30:00.0000000

Format result as you see fit.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

getSupportFragmentManager() is not part of Fragment, so you cannot get it here that way. You can get it from parent Activity (so in onAttach() the earliest) using normal

activity.getSupportFragmentManager();

or you can try getChildFragmentManager(), which is in scope of Fragment, but requires API17+

Hide strange unwanted Xcode logs

This is still not fixed in Xcode Version 8.0 beta 2 (8S162m) for me and extra logs are also appearing in the Xcode console

** EDIT 8/1/16: This has been acknowledged in the release notes for Xcode 8 Beta 4 (8S188o) as an issues still persisting.

Known Issues in Xcode 8 beta 4 – IDE

Debugging

• Xcode Debug Console shows extra logging from system frameworks when debugging applications in the Simulator. (27331147, 26652255)

Presumably this will be resolved by the GM release. Until then patience and although not ideal but a workaround I'm using is below...

Similar to the previous answer I am having to:

  • prefix my print logs with some kind of special character (eg * or ^ or ! etc etc)

  • Then use the search box on the bottom right of the console pane to filter my console logs by inputing my chosen special character to get the console to display my print logs as intended

console

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Getting each individual digit from a whole integer

This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.

It also works for wider types or signed types (with positive values) with appropriate type changes.

This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)

#include <limits.h>
#include <stdio.h>

int
main (void)
{
  unsigned int score = 42;   // Works for score in [0, UINT_MAX]

  printf ("score via printf:     %u\n", score);   // For validation

  printf ("score digit by digit: ");
  unsigned int div = 1;
  unsigned int digit_count = 1;
  while ( div <= score / 10 ) {
    digit_count++;
    div *= 10;
  }
  while ( digit_count > 0 ) {
    printf ("%d", score / div);
    score %= div;
    div /= 10;
    digit_count--;
  }
  printf ("\n");

  return 0;
}

How to replace multiple patterns at once with sed?

I believe this should solve your problem. I may be missing a few edge cases, please comment if you notice one.

You need a way to exclude previous substitutions from future patterns, which really means making outputs distinguishable, as well as excluding these outputs from your searches, and finally making outputs indistinguishable again. This is very similar to the quoting/escaping process, so I'll draw from it.

  • s/\\/\\\\/g escapes all existing backslashes
  • s/ab/\\b\\c/g substitutes raw ab for escaped bc
  • s/bc/\\a\\b/g substitutes raw bc for escaped ab
  • s/\\\(.\)/\1/g substitutes all escaped X for raw X

I have not accounted for backslashes in ab or bc, but intuitively, I would escape the search and replace terms the same way - \ now matches \\, and substituted \\ will appear as \.

Until now I have been using backslashes as the escape character, but it's not necessarily the best choice. Almost any character should work, but be careful with the characters that need escaping in your environment, sed, etc. depending on how you intend to use the results.

Excel VBA For Each Worksheet Loop

Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.

This will get you into the worksheet you want to work on.

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Styling Google Maps InfoWindow

I have design google map infowindow with image & some content as per below.

enter image description here

map_script (Just for infowindow html reference)

for (i = 0; i < locations.length; i++) { 
    var latlng = new google.maps.LatLng(locations[i][1], locations[i][2]);
    marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: "<?php echo plugins_url( 'assets/img/map-pin.png', ELEMENTOR_ES__FILE__ ); ?>"
    });

    var property_img = locations[i][6],
    title = locations[i][0],
    price = locations[i][3],
    bedrooms = locations[i][4],
    type = locations[i][5],
    listed_on = locations[i][7],
    prop_url = locations[i][8];

    content = "<div class='map_info_wrapper'><a href="+prop_url+"><div class='img_wrapper'><img src="+property_img+"></div>"+
    "<div class='property_content_wrap'>"+
    "<div class='property_title'>"+
    "<span>"+title+"</span>"+
    "</div>"+

    "<div class='property_price'>"+
    "<span>"+price+"</span>"+
    "</div>"+

    "<div class='property_bed_type'>"+
    "<span>"+bedrooms+"</span>"+
    "<ul><li>"+type+"</li></ul>"+
    "</div>"+

    "<div class='property_listed_date'>"+
    "<span>Listed on "+listed_on+"</span>"+
    "</div>"+
    "</div></a></div>";

    google.maps.event.addListener(marker, 'click', (function(marker, content, i) {
        return function() {
            infowindow.setContent(content);
            infowindow.open(map, marker);
        }
    })(marker, content, i));
}

Most important thing is CSS

 #propertymap .gm-style-iw{
    box-shadow:none;
    color:#515151;
    font-family: "Georgia", "Open Sans", Sans-serif;
    text-align: center;
    width: 100% !important;
    border-radius: 0;
    left: 0 !important;
    top: 20px !important;
}

 #propertymap .gm-style > div > div > div > div > div > div > div {
    background: none!important;
}

.gm-style > div > div > div > div > div > div > div:nth-child(2) {
     box-shadow: none!important;
}
 #propertymap .gm-style-iw > div > div{
    background: #FFF!important;
}

 #propertymap .gm-style-iw a{
    text-decoration: none;
}

 #propertymap .gm-style-iw > div{
    width: 245px !important
}

 #propertymap .gm-style-iw .img_wrapper {
    height: 150px;  
    overflow: hidden;
    width: 100%;
    text-align: center;
    margin: 0px auto;
}

 #propertymap .gm-style-iw .img_wrapper > img {
    width: 100%;
    height:auto;
}

 #propertymap .gm-style-iw .property_content_wrap {
    padding: 0px 20px;
}

 #propertymap .gm-style-iw .property_title{
    min-height: auto;
}

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

jquery: $(window).scrollTop() but no $(window).scrollBottom()

var scrollBottom =
    $(document).height() - $(window).height() - $(window).scrollTop();

I think it is better to get bottom scroll.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.

enter image description here

Windows batch files: .bat vs .cmd?

Slightly off topic, but have you considered Windows Scripting Host? You might find it nicer.

WPF: Setting the Width (and Height) as a Percentage Value

IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value (percentage) and parameter (parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:

public class SizePercentageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter == null)
            return 0.7 * value.ToDouble();

        string[] split = parameter.ToString().Split('.');
        double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
        return value.ToDouble() * parameterDouble;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
        return null;
    }
}

XAML:

<UserControl.Resources>
    <m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>

<ScrollViewer VerticalScrollBarVisibility="Auto"
          HorizontalScrollBarVisibility="Disabled"
          Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
          Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

I would not have expected this case to be optimized at all. It can't be very often where an expression contains subexpressions that can be regrouped to remove entire operations. I would expect compiler writers to invest their time in areas which would be more likely to result in noticeable improvements, rather than covering a rarely encountered edge case.

I was surprised to learn from the other answers that this expression could indeed be optimized with the proper compiler switches. Either the optimization is trivial, or it is an edge case of a much more common optimization, or the compiler writers were extremely thorough.

There's nothing wrong with providing hints to the compiler as you've done here. It's a normal and expected part of the micro-optimization process to rearrange statements and expressions to see what differences they will bring.

While the compiler may be justified in considering the two expressions to deliver inconsistent results (without the proper switches), there's no need for you to be bound by that restriction. The difference will be incredibly tiny - so much so that if the difference matters to you, you should not be using standard floating point arithmetic in the first place.

How to animate the change of image in an UIImageView?

As of iOS 5 this one is far more easy:

[newView setAlpha:0.0];
[UIView animateWithDuration:0.4 animations:^{
    [newView setAlpha:0.5];
}];

Converting String to Cstring in C++

vector<char> toVector( const std::string& s ) {
  string s = "apple";  
  vector<char> v(s.size()+1);
  memcpy( &v.front(), s.c_str(), s.size() + 1 );
  return v;
}
vector<char> v = toVector(std::string("apple"));

// what you were looking for (mutable)
char* c = v.data();

.c_str() works for immutable. The vector will manage the memory for you.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

Standard SQL provides the MERGE statement for this task. Not all DBMS support the MERGE statement.

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

Where can I find error log files?

You can use "lsof" to find open logfiles on your system. lsof just gives you a list of all open files.

Use grep for "log" ... use grep again for "php" (if the filename contains the strings "log" and "php" like in "php_error_log" and you are root user you will find the files without knowing the configuration).

        root@lnx-work:~# lsof |grep log
        ... snip
        gmain     12148 12274       user   13r      REG              252,1    32768     661814 /home/user/.local/share/gvfs-metadata/home-11ab0393.log
        gmain     12148 12274       user   21r      REG              252,1    32768     662622 /home/user/.local/share/gvfs-metadata/root-56222fe2.log
        gvfs-udis 12246             user  mem       REG              252,1    55384     790567 /lib/x86_64-linux-gnu/libsystemd-login.so.0.7.1
==> apache 12333             user  mem       REG              252,1    55384     790367 /var/log/http/php_error_log**
        ... snip 

        root@lnx-work:~# lsof |grep log |grep php 
        **apache 12333             user  mem       REG              252,1    55384     790367 /var/log/http/php_error_log**
        ... snip 

Also see this article on finding open logfiles: Find open logfiles on a linux system

Format LocalDateTime with Timezone in Java8

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));

How to view files in binary from bash?

If you want to open binary files (in CentOS 7):

strings <binary_filename>

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Clean your maven cache and rerun:

mvn dependency:purge-local-repository

Find max and second max salary for a employee table MySQL

For unique salaries (i.e. first can't be same as second):

SELECT
  MAX( s.salary ) AS max_salary,
  (SELECT
     MAX( salary ) 
   FROM salaries
   WHERE salary <> MAX( s.salary ) 
   ORDER BY salary DESC 
   LIMIT 1
  ) AS 2nd_max_salary
FROM salaries s

And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)

How print out the contents of a HashMap<String, String> in ascending order based on its values?

It's time to add some lambdas:

codes.entrySet()
    .stream()
    .sorted(Comparator.comparing(Map.Entry::getValue))
    .forEach(System.out::println);

Aborting a shell script if any command returns a non-zero value

To add to the accepted answer:

Bear in mind that set -e sometimes is not enough, specially if you have pipes.

For example, suppose you have this script

#!/bin/bash
set -e 
./configure  > configure.log
make

... which works as expected: an error in configure aborts the execution.

Tomorrow you make a seemingly trivial change:

#!/bin/bash
set -e 
./configure  | tee configure.log
make

... and now it does not work. This is explained here, and a workaround (Bash only) is provided:

#!/bin/bash
set -e 
set -o pipefail

./configure  | tee configure.log
make

Pip Install not installing into correct directory?

From the comments to the original question, it seems that you have multiple versions of python installed and that pip just goes to the wrong version.

First, to know which version of python you're using, just type which python. You should either see:

which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python

if you're going to the right version of python, or:

which python
/usr/bin/python

If you're going to the 'wrong' version. To make pip go to the right version, you first have to change the path:

 export PATH=/Library/Frameworks/Python.framework/Versions/2.7/bin/python:${PATH}

typing 'which python' would now get you to the right result. Next, install pip (if it's not already installed for this installation of python). Finally, use it. you should be fine now.

lodash: mapping array to object

Yep it is here, using _.reduce

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];

_.reduce(params , function(obj,param) {
 obj[param.name] = param.input
 return obj;
}, {});

Using fonts with Rails asset pipeline

If you don't want to keep track of moving your fonts around:

# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(eot|svg|ttf|woff)\z/
    true
  end
}

convert a char* to std::string

char* data;
std::string myString(data);

Google Maps: how to get country, state/province/region, city given a lat/long value?

I used this question as a starting point for my own solution. Thought it was appropriate to contribute my code back since its smaller than tabacitu's

Dependencies:

Code:

if(geoPosition.init()){  

    var foundLocation = function(city, state, country, lat, lon){
        //do stuff with your location! any of the first 3 args may be null
        console.log(arguments);
    }

    var geocoder = new google.maps.Geocoder(); 
    geoPosition.getCurrentPosition(function(r){
        var findResult = function(results, name){
            var result =  _.find(results, function(obj){
                return obj.types[0] == name && obj.types[1] == "political";
            });
            return result ? result.short_name : null;
        };
        geocoder.geocode({'latLng': new google.maps.LatLng(r.coords.latitude, r.coords.longitude)}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK && results.length) {
                results = results[0].address_components;
                var city = findResult(results, "locality");
                var state = findResult(results, "administrative_area_level_1");
                var country = findResult(results, "country");
                foundLocation(city, state, country, r.coords.latitude, r.coords.longitude);
            } else {
                foundLocation(null, null, null, r.coords.latitude, r.coords.longitude);
            }
        });
    }, { enableHighAccuracy:false, maximumAge: 1000 * 60 * 1 });
}

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

Get current language in CultureInfo

To get the 2 chars ISO 639-1 language identifier use:

System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

How to normalize a 2-dimensional numpy array in python less verbose?

Or using lambda function, like

>>> vec = np.arange(0,27,3).reshape(3,3)
>>> import numpy as np
>>> norm_vec = map(lambda row: row/np.linalg.norm(row), vec)

each vector of vec will have a unit norm.

Java - Writing strings to a CSV file

I think this is a simple code in java which will show the string value in CSV after compile this code.

public class CsvWriter {

    public static void main(String args[]) {
        // File input path
        System.out.println("Starting....");
        File file = new File("/home/Desktop/test/output.csv");
        try {
            FileWriter output = new FileWriter(file);
            CSVWriter write = new CSVWriter(output);

            // Header column value
            String[] header = { "ID", "Name", "Address", "Phone Number" };
            write.writeNext(header);
            // Value
            String[] data1 = { "1", "First Name", "Address1", "12345" };
            write.writeNext(data1);
            String[] data2 = { "2", "Second Name", "Address2", "123456" };
            write.writeNext(data2);
            String[] data3 = { "3", "Third Name", "Address3", "1234567" };
            write.writeNext(data3);
            write.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        System.out.println("End.");

    }
}

ClientScript.RegisterClientScriptBlock?

The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.

Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )

Guessing the problem

If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.

Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.

Rails ActiveRecord date between

There should be a default active record behavior on this I reckon. Querying dates is hard, especially when timezones are involved.

Anyway, I use:

  scope :between, ->(start_date=nil, end_date=nil) {
    if start_date && end_date
      where("#{self.table_name}.created_at BETWEEN :start AND :end", start: start_date.beginning_of_day, end: end_date.end_of_day)
    elsif start_date
      where("#{self.table_name}.created_at >= ?", start_date.beginning_of_day)
    elsif end_date
      where("#{self.table_name}.created_at <= ?", end_date.end_of_day)
    else
      all
    end
  }

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

Install Application programmatically on Android

This can help others a lot!

First:

private static final String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyAppFolderInStorage/";

private void install() {
    File file = new File(APP_DIR + fileName);

    if (file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri downloadedApk = FileProvider.getUriForFile(getContext(), "ir.greencode", file);
            intent.setDataAndType(downloadedApk, type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        getContext().startActivity(intent);
    } else {
        Toast.makeText(getContext(), "?File not found!", Toast.LENGTH_SHORT).show();
    }
}

Second: For android 7 and above you should define a provider in manifest like below!

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="ir.greencode"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/paths" />
    </provider>

Third: Define path.xml in res/xml folder like below! I'm using this path for internal storage if you want to change it to something else there is a few way! You can go to this link: FileProvider

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="your_folder_name" path="MyAppFolderInStorage/"/>
</paths>

Forth: You should add this permission in manifest:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

Allows an application to request installing packages. Apps targeting APIs greater than 25 must hold this permission in order to use Intent.ACTION_INSTALL_PACKAGE.

Please make sure the provider authorities are the same!


What is the point of "final class" in Java?

In Java, items with the final modifier cannot be changed!

This includes final classes, final variables, and final methods:

  • A final class cannot be extended by any other class
  • A final variable cannot be reassigned another value
  • A final method cannot be overridden

How can moment.js be imported with typescript?

Still broken? Try uninstalling @types/moment.

So, I removed @types/moment package from the package.json file and it worked using:

import * as moment from 'moment'

Newer versions of moment don't require the @types/moment package as types are already included.

Handling NULL values in Hive

What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.

How to convert a string from uppercase to lowercase in Bash?

Why not execute in backticks ?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

Force browser to clear cache

Not sure if that might really help you but that's how caching should work on any browser. When the browser request a file, it should always send a request to the server unless there is a "offline" mode. The server will read some parameters like date modified or etags.

The server will return a 304 error response for NOT MODIFIED and the browser will have to use its cache. If the etag doesn't validate on server side or the modified date is below the current modified date, the server should return the new content with the new modified date or etags or both.

If there is no caching data sent to the browser, I guess the behavior is undetermined, the browser may or may not cache file that don't tell how they are cached. If you set caching parameters in the response it will cache your files correctly and the server then may choose to return a 304 error, or the new content.

This is how it should be done. Using random params or version number in urls is more like a hack than anything.

http://www.checkupdown.com/status/E304.html http://en.wikipedia.org/wiki/HTTP_ETag http://www.xpertdeveloper.com/2011/03/last-modified-header-vs-expire-header-vs-etag/

After reading I saw that there is also a expire date. If you have problem, it might be that you have a expire date set up. In other words, when the browser will cache your file, since it has a expiry date, it shouldn't have to request it again before that date. In other words, it will never ask the file to the server and will never receive a 304 not modified. It will simply use the cache until the expiry date is reached or cache is cleared.

So that is my guess, you have some sort of expiry date and you should use last-modified etags or a mix of it all and make sure that there is no expire date.

If people tends to refresh a lot and the file doesn't get changed a lot, then it might be wise to set a big expiry date.

My 2 cents!

Assert an object is a specific type

Solution for JUnit 5 for Kotlin!

Example for Hamcrest:

import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.jupiter.api.Test

class HamcrestAssertionDemo {

    @Test
    fun assertWithHamcrestMatcher() {
        val subClass = SubClass()
        MatcherAssert.assertThat(subClass, CoreMatchers.instanceOf<Any>(BaseClass::class.java))
    }

}

Example for AssertJ:

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

class AssertJDemo {

    @Test
    fun assertWithAssertJ() {
        val subClass = SubClass()
        assertThat(subClass).isInstanceOf(BaseClass::class.java)
    }

}

When I catch an exception, how do I get the type, file, and line number?

Without any imports, but also incompatible with imported modules:

try:
    raise TypeError("Hello, World!")  # line 2
except Exception as e:
    print(
        type(e).__name__,          # TypeError
        __file__,                  # /tmp/example.py
        e.__traceback__.tb_lineno  # 2
    )

$ python3 /tmp/example.py
TypeError /tmp/example.py 2

To reiterate, this does not work across imports or modules, so if you do import X; try: X.example(); then the filename and line number will point to the line containing X.example() instead of the line where it went wrong within X.example(). If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something like e[-1].filename, but no such luck), please improve this answer.

How to make button look like a link?

If you don't mind using twitter bootstrap I suggest you simply use the link class.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">_x000D_
<button type="button" class="btn btn-link">Link</button>
_x000D_
_x000D_
_x000D_

I hope this helps somebody :) Have a nice day!

Generating (pseudo)random alpha-numeric strings

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();

How to replace sql field value

Try this query it ll change the records ends with .com

 UPDATE tablename SET email = replace(email, '.com', '.org') WHERE  email LIKE '%.com';

Cannot run the macro... the macro may not be available in this workbook

I had the same problem as OP and found was due to the options declaration being misspelled:

' Comment comment  

Options Explicit  

Sub someMacroMakechart()

in a sub module, instead of correct;

' Comment comment  

Option Explicit  

Sub someMacroMakechart()

How to list files inside a folder with SQL Server

Very easy, just use the SQLCMD-syntax.

Remember to enable SQLCMD-mode in the SSMS, look under Query -> SQLCMD Mode

Try execute:

!!DIR
!!:GO

or maybe:
!!DIR "c:/temp"
!!:GO

Best way to parse command line arguments in C#?

There is a command line argument parser at http://www.codeplex.com/commonlibrarynet

It can parse arguments using
1. attributes
2. explicit calls
3. single line of multiple arguments OR string array

It can handle things like the following:

-config:Qa -startdate:${today} -region:'New York' Settings01

It's very easy to use.

How to copy Java Collections list

Strings can be deep copied with

List<String> b = new ArrayList<String>(a);

because they are immutable. Every other Object not --> you need to iterate and do a copy by yourself.

How to deep copy a list?

I believe a lot of programmers have run into one or two interview problems where they are asked to deep copy a linked list, however this problem is harder than it sounds!

in python, there is a module called "copy" with two useful functions

import copy
copy.copy()
copy.deepcopy()

copy() is a shallow copy function, if the given argument is a compound data structure, for instance a list, then python will create another object of the same type (in this case, a new list) but for everything inside old list, only their reference is copied

# think of it like
newList = [elem for elem in oldlist]

Intuitively, we could assume that deepcopy() would follow the same paradigm, and the only difference is that for each elem we will recursively call deepcopy, (just like the answer of mbcoder)

but this is wrong!

deepcopy() actually preserve the graphical structure of the original compound data:

a = [1,2]
b = [a,a] # there's only 1 object a
c = deepcopy(b)

# check the result
c[0] is a # return False, a new object a' is created
c[0] is c[1] # return True, c is [a',a'] not [a',a'']

this is the tricky part, during the process of deepcopy() a hashtable(dictionary in python) is used to map: "old_object ref onto new_object ref", this prevent unnecessary duplicates and thus preserve the structure of the copied compound data

official doc

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

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

help(input) shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:

input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

You could reproduce it using an empty file:

$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError: EOF when reading a line

You could use /dev/null or nul (Windows) as an empty file for reading. os.devnull shows the name that is used by your OS:

$ python3 -c "import os; print(os.devnull)"
/dev/null

Note: input() happily accepts input from a file/pipe. You don't need stdin to be connected to the terminal:

$ echo abc | python3 -c "print(input()[::-1])"
cba

Either handle EOFError in your code:

try:
    reply = input('Enter text')
except EOFError:
    break

Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file

C/C++ switch case with string

Ruslik's suggestion to use source generation seems like a good thing to me. However, I wouldn't go with the concept of "main" and "generated" source files. I'd rather have one file with code almost identical to yours:

h=_myhash (mystring);
switch (h)
{
case 66452: // = hash("Vasia")
   .......
case 1342537: // = hash("Petya")
   ........
}

The next thing I'd do, I'd write a simple script. Perl is good for such kind of things, but nothing stops you even from writing a simple program in C/C++ if you don't want to use any other languages. This script, or program, would take the source file, read it line-by-line, find all those case NUMBERS: // = hash("SOMESTRING") lines (use regular expressions here), replace NUMBERS with the actual hash value and write the modified source into a temporary file. Finally, it would back up the source file and replace it with the temporary file. If you don't want your source file to have a new time stamp each time, the program could check if something was actually changed and if not, skip the file replacement.

The last thing to do is to integrate this script into the build system used, so you won't accidentally forget to launch it before building the project.

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

SOAP or REST for Web Services?

REST is an architecture, SOAP is a protocol.

That's the first problem.

You can send SOAP envelopes in a REST application.

SOAP itself is actually pretty basic and simple, it's the WSS-* standards on top of it that make it very complex.

If your consumers are other applications and other servers, there's a lot of support for the SOAP protocol today, and the basics of moving data is essentially a mouse-click in modern IDEs.

If your consumers are more likely to be RIAs or Ajax clients, you will probably want something simpler than SOAP, and more native to the client (notably JSON).

JSON packets sent over HTTP is not necessarily a REST architecture, it's just messages to URLs. All perfectly workable, but there are key components to the REST idiom. It is easy to confuse the two however. But just because you're talking HTTP requests does not necessarily mean you have a REST architecture. You can have a REST application with no HTTP at all (mind, this is rare).

So, if you have servers and consumers that are "comfortable" with SOAP, SOAP and WSS stack can serve you well. If you're doing more ad hoc things and want to better interface with web browsers, then some lighter protocol over HTTP can work well also.

How to exit from ForEach-Object in PowerShell

Below is a suggested approach to Question #1 which I use if I wish to use the ForEach-Object cmdlet. It does not directly answer the question because it does not EXIT the pipeline. However, it may achieve the desired effect in Q#1. The only drawback an amateur like myself can see is when processing large pipeline iterations.

    $zStop = $false
    (97..122) | Where-Object {$zStop -eq $false} | ForEach-Object {
    $zNumeric = $_
    $zAlpha = [char]$zNumeric
    Write-Host -ForegroundColor Yellow ("{0,4} = {1}" -f ($zNumeric, $zAlpha))
    if ($zAlpha -eq "m") {$zStop = $true}
    }
    Write-Host -ForegroundColor Green "My PSVersion = 5.1.18362.145"

I hope this is of use. Happy New Year to all.

Redirection of standard and error output appending to the same log file

Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.

First let's generate a nice filename, but that's really just for being pedantic:

$name = "sync_common"
$currdate = get-date -f yyyy-MM-dd
$logfile = "c:\scripts\$name\log\$name-$currdate.txt"

And here's where the trick begins:

start-transcript -append -path $logfile

write-output "starting sync"
robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
some_other.exe /exeparams 2>&1 | Write-Output
...
write-output "ending sync"

stop-transcript

With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.

In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.

Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

How do I use DateTime.TryParse with a Nullable<DateTime>?

Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:

DateTime? d = DateTime.Parse("some valid text");

Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

How to check if a table exists in MS Access for vb macros

Setting a reference to the Microsoft Access 12.0 Object Library allows us to test if a table exists using DCount.

Public Function ifTableExists(tblName As String) As Boolean

    If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 1 Then

        ifTableExists = True

    End If

End Function

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

You can also "fix" this by replacing the image with its inline Base64 representation:

img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only.

NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

Is String.Contains() faster than String.IndexOf()?

Contains(s2) is many times (in my computer 10 times) faster than IndexOf(s2) because Contains uses StringComparison.Ordinal that is faster than the culture sensitive search that IndexOf does by default (but that may change in .net 4.0 http://davesbox.com/archive/2008/11/12/breaking-changes-to-the-string-class.aspx).

Contains has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear.

What regular expression will match valid international phone numbers?

This works for me, without 00, 001, 0011 etc prefix though:

/^\+*(\d{3})*[0-9,\-]{8,}/

Attempt to write a readonly database - Django w/ SELinux error

I faced the same problem but on Ubuntu Server. So all I did is changed to superuser before I activate virtual environment for django and then I ran the django server. It worked fine for me.

First copy paste

sudo su

Then activate the virtual environment if you have one.

source myvenv/bin/activate

At last run your django server.

python3 manage.py runserver

Hope, this will help you.

Recursively looping through an object to build a property list

Solution to flatten properties and arrays as well.

Example input:

{
  obj1: {
    prop1: "value1",
    prop2: "value2"
  },
  arr1: [
    "value1",
    "value2"
  ]
}

Output:

"arr1[0]": "value1"
"arr1[1]": "value2"
"obj1.prop1": "value1"
"obj1.prop2": "value2"

Source code:

flatten(object, path = '', res = undefined) {
      if (!Array.isArray(res)) {
          res = [];
      }
      if (object !== null && typeof object === 'object') {
          if (Array.isArray(object)) {
              for (let i = 0; i < object.length; i++) {
                  this.flatten(object[i], path + '[' + i + ']', res)
              }
          } else {
              const keys = Object.keys(object)
              for (let i = 0; i < keys.length; i++) {
                  const key = keys[i]
                  this.flatten(object[key], path ? path + '.' + key : key, res)
              }
          }
      } else {
          if (path) {
              res[path] = object
          }
      }
      return res
  }

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from http://wiki.nginx.org/LoadBalanceExample is:

http {
  upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;    
    server 127.0.0.1:8003;
  }

  server {
    listen 80;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
    }
  }
}

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

Disable firefox same origin policy

As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases

In the options panel you can configure which header to inject and specific website to have it enabled automatically.

enter image description here

Add ArrayList to another ArrayList in java

Your Problem

Mainly, you've got 2 major problems:

You are using adding a List of Strings. You want a List containing Lists of Strings.

Note as well that when you invoke this:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.

You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.

So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

  • i = 0

    nodes: [PropertyStart,a,b,c,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd]]
    
  • i = 1

    nodes: [PropertyStart,d,e,f,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
    
  • i = 2

    nodes: [PropertyStart,g,h,i,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
    
  • and so on...

Some Other Corrections

Follow the Java Naming Conventions

Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).

Learn a Bit More About Types

You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.

There's a difference between a type, an interface, and an implementation.

Use Generics for Stronger Typing in Collections

Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.

So your code becomes:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code

You could do away with the nodeList entirely, and write the following once you've fixed your types:

list.add(nodes);

Use the Right Scope

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).

SSCCE

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

Calculating average of an array list?

With Java 8 it is a bit easier:

OptionalDouble average = marks
            .stream()
            .mapToDouble(a -> a)
            .average();

Thus your average value is average.getAsDouble()

return average.isPresent() ? average.getAsDouble() : 0; 

Filter Linq EXCEPT on properties

I like the Except extension methods, but the original question doesn't have symmetric key access and I prefer Contains (or the Any variation) to join, so with all credit to azuneca's answer:

public static IEnumerable<T> Except<T, TKey>(this IEnumerable<TKey> items,
    IEnumerable<T> other, Func<T, TKey> getKey) {

    return from item in items
        where !other.Contains(getKey(item))
        select item;
}

Which can then be used like:

var filteredApps = unfilteredApps.Except(excludedAppIds, ua => ua.Id);

Also, this version allows for needing a mapping for the exception IEnumerable by using a Select:

var filteredApps = unfilteredApps.Except(excludedApps.Select(a => a.Id), ua => ua.Id);

Enable/disable buttons with Angular

export class ClassComponent implements OnInit {
  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]


checkCurrentLession(current){

 this.classes.forEach((obj)=>{
    if(obj.currentLession == current){
      return true;
    }

  });
  return false;
}


<ul class="table lessonOverview">
        <li>
          <p>Lesson 1</p>
          <button [routerLink]="['/lesson1']" 
             [disabled]="checkCurrentLession(1)" class="primair">
               Start lesson</button>
        </li>
        <li>
          <p>Lesson 2</p>
          <button [routerLink]="['/lesson2']" 
             [disabled]="!checkCurrentLession(2)" class="primair">
               Start lesson</button>
        </li>
     </ul>

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads:

  • singleton
  • session (or request)
  • thread pool of jobs

The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request.

Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case).


I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore?

Return datetime object of previous month

import datetime
date_str = '08/01/2018'
format_str = '%d/%m/%Y'
datetime_obj = datetime.datetime.strptime(date_str, format_str)   
datetime_obj.replace(month=datetime_obj.month-1)

Simple solution, no need for special libraries.

Can I call a base class's virtual function if I'm overriding it?

Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:

struct Base
{
    virtual int Foo()
    {
        return -1;
    }
};

struct Derived : public Base
{
    virtual int Foo()
    {
        return -2;
    }
};

int main(int argc, char* argv[])
{
    Base *x = new Derived;

    ASSERT(-2 == x->Foo());

    //syntax is trippy but it works
    ASSERT(-1 == x->Base::Foo());

    return 0;
}

Vim delete blank lines

I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?

Here's the easiest one that I found that works on Vim in Windows 7:

:v/\S/d

Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines

Spring RequestMapping for controllers that produce and consume JSON

As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

Yes, there is such a way. You can create a meta annotation like following:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

Then you can use the default settings or even override them as you want:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

good example of Javadoc

I use a small set of documentation patterns:

  • always documenting about thread-safety
  • always documenting immutability
  • javadoc with examples (like Formatter)
  • @Deprecation with WHY and HOW to replace the annotated element

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How should I choose an authentication library for CodeIgniter?

I'm the developer of Redux Auth and some of the issues you mentioned have been fixed in the version 2 beta. You can download this off the offcial website with a sample application too.

  • Requires autoloading (impeding performance)
  • Uses the inherently unsafe concept of 'security questions'. Dealbreaker!

Security questions are now not used and a simpler forgotten password system has been put in place.

  • Return types are a bit of a hodgepodge of true, false, error and success codes

This was fixed in version 2 and returns boolean values. I hated the hodgepodge as much as you.

  • Doesn't hook into CI's validation system

The sample application uses the CI's validation system.

  • Doesn't allow a user to resend a 'lost password' code

Work in progress

I also implemented some other features such as email views, this gives you the choice of being able to use the CodeIgniter helpers in your emails.

It's still a work in progress so if have any more suggestions please keep them coming.

-Popcorn

Ps : Thanks for recommending Redux.

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Get query string parameters url values with jQuery / Javascript (querystring)

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

//URL is http://www.example.com/mypage?ref=registration&[email protected]

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //[email protected]

Use as you will.

How to use UIScrollView in Storyboard

Here are the steps with Auto Layout that worked for me on XCode 8.2.1.

  1. Select Size Inspector of View Controller, and change Simulated Size to Freeform with height 1000 instead of Fixed.
  2. Rename the view of View Controller as RootView.
  3. Drag a Scroll View as subview of RootView and rename it as ScrollView.
  4. Add constraints for ScrollView:
    • ScrollView[Top, Bottom, Leading, Trailing] = RootView[Top, Bottom, Leading, Trailing]
  5. Drag a Vertical Stack View as subview of ScrollView and rename it as ContentView.
  6. Add constraints for ContentView:
    • ContentView.height = 1000
    • ContentView[Top, Bottom, Leading, Trailing, Width] = ScrollView[Top, Bottom, Leading, Trailing, Width]
  7. Select Attributes Inspector of ContentView, and change Distribution to Fill Equally instead of Fill.
  8. Drag a View as subview of ContentView and rename it as RedView.
  9. Set Red as the background of RedView.
  10. Drag a View as subview of ContentView and rename it as BlueView.
  11. Set Blue as the background of BlueView.
  12. Select RootView, and click Update Frames button.
    • Update Frames is a new button in Xcode8, instead of Resolve Auto Layout Issues button. It looks like a refresh button, located in the control bar below the Storyboard: Update Frames Button

View hierarchy:

  • RootView
    • ScrollView
      • ContentView
        • RedView
        • BlueView

View Controller Scene (Height: 1000):

scene

Run on iPhone7 (Height: 1334 / 2):

demo

Function or sub to add new row and data to table

Minor variation on Geoff's answer.

New Data in Array:

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

New Data in Horizontal Range:

Sub AddDataRow(tableName As String, NewData As Range)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last table row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Copy NewData to new table record
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    lastRow.Value = NewData.Value
End Sub

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

C# ASP.NET MVC Return to Previous Page

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

An example: Imagine that you have a Vehicle Controller with actions

Index

Details

Edit

and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
     ..............
     ..............
     public string ReturnUrl {get;set;}
}



Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
        </div>
    </form>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
    {
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
            else
                viewModel.ReturnUrl = "Index";
            return View(viewModel);
        }



[HttpPost]
    public IActionResult Edit(VehicleViewModel model, string previous)
    {
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
            else
                model.ReturnUrl = "Index";
            ............. 
            .............
            return RedirectToAction(model.ReturnUrl);
    }

How to drop a unique constraint from table column?

This statement works for me

  ALTER TABLE table_name DROP UNIQUE (column_name);

Passing an array as an argument to a function in C

In C, except for a few special cases, an array reference always "decays" to a pointer to the first element of the array. Therefore, it isn't possible to pass an array "by value". An array in a function call will be passed to the function as a pointer, which is analogous to passing the array by reference.

EDIT: There are three such special cases where an array does not decay to a pointer to it's first element:

  1. sizeof a is not the same as sizeof (&a[0]).
  2. &a is not the same as &(&a[0]) (and not quite the same as &a[0]).
  3. char b[] = "foo" is not the same as char b[] = &("foo").

Show Error on the tip of the Edit Text Android

I got the solution of my problem Hope this will help others also.I have used onTextChnaged it invokes When an object of a type is attached to an Editable, its methods will be called when the text is changed.

public class MainActivity extends Activity {
    TextView emailId;
    ImageView continuebooking;
    EditText firstName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        emailId = (TextView)findViewById(R.id.emailid);
        continuebooking = (ImageView)findViewById(R.id.continuebooking);
        firstName= (EditText)findViewById(R.id.firstName);
        emailId.setText("[email protected]");
        setTittle();
        continuebooking.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if(firstName.getText().toString().trim().equalsIgnoreCase("")){
                    firstName.setError("Enter FirstName");
                }

            }
        });
        firstName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                firstName.setError(null);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                firstName.setError(null);

            }
        });
    }

how to bypass Access-Control-Allow-Origin?

It's a really bad idea to use *, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.

class CorsAccessControl
{
    private $allowed = array();

    /**
     * Always adds your own domain with the current ssl settings.
     */
    public function __construct()
    {
        // Add your own domain, with respect to the current SSL settings.
        $this->allowed[] = 'http'
            . ( ( array_key_exists( 'HTTPS', $_SERVER )
                && $_SERVER['HTTPS'] 
                && strtolower( $_SERVER['HTTPS'] ) !== 'off' ) 
                    ? 's' 
                    : null )
            . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * Optionally add additional domains. Each is only added one time.
     */
    public function add($domain)
    {
        if ( !in_array( $domain, $this->allowed )
        {
            $this->allowed[] = $domain;
        }
    /**
     * Send 'em all as one header so no browsers grumble about it.
     */
    public function send()
    {
        $domains = implode( ', ', $this->allowed );
        header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
    }
}

Usage:

$cors = new CorsAccessControl();

// If you are only authorizing your own domain:
$cors->send();

// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
    $cors->add($domain);
}
$cors->send();

You get the idea.

What is the simplest C# function to parse a JSON string into an object?

DataContractJsonSerializer serializer = 
    new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);

You could also use the JavaScriptSerializer, but DataContractJsonSerializer is supposedly better able to handle complex types.

Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer since it is hard baked for WCF.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

You have to drag the file using the right mouse button. The moment you release the file to the new destination you will observe the option:

SVN move versioned files here.

Just select this option and you are done !!

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

How to process each output line in a loop?

I would suggest using awk instead of grep + something else here.

awk '$0~/xyz/{ //your code goes here}' abc.txt

Remove scrollbars from textarea

style="overflow: hidden" and style="resize: none" were the ones that did the trick.

how to load url into div tag

You need to use an iframe.

<html>
<head>
<script type="text/javascript">
    $(document).ready(function(){
    $("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html

RecyclerView - Get view at particular position

You can as well do this, this will help when you want to modify a view after clicking a recyclerview position item

@Override
public void onClick(View view, int position) {

            View v =  rv_notifications.getChildViewHolder(view).itemView;
            TextView content = v.findViewById(R.id.tv_content);
            content.setText("Helloo");

        }

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

In my case, I was dealing with a file that was generated by hadoop on a linux box. When I tried to import to sql I had this issue. The fix wound up being to use the hex value for 'line feed' 0x0a. It also worked for bulk insert

bulk insert table from 'file' 
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0a')

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

Since there is no programmatic way to mimic minimal-ui, we have come up with a different workaround, using calc() and known iOS address bar height to our advantage:

The following demo page (also available on gist, more technical details there) will prompt user to scroll, which then triggers a soft-fullscreen (hide address bar/menu), where header and content fills the new viewport.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }

        html {
            background-color: red;
        }

        body {
            background-color: blue;
            margin: 0;
        }

        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }

        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }

        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }

        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }

            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        window.addEventListener('scroll', function(ev) {

            if (timeout) {
                clearTimeout(timeout);
            }

            timeout = setTimeout(function() {

                if (window.scrollY > 0) {
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';
                }

            }, 200);

        });
    </script>
</head>
<body>

    <div class="header">
        <p>header</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>
</html>

Move SQL Server 2008 database files to a new folder location

Some notes to complement the ALTER DATABASE process:

1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:

   USE master SELECT name, physical_name FROM sys.master_files

2) You can move manually the files with CMD move command:

Move "Source" "Destination"

Example:

md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"

3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.

You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData

USE [master]

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'

GO

Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

What does the "__block" keyword mean?

It means that the variable it is a prefix to is available to be used within a block.

How to read the last row with SQL Server

You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:

SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1

The ORDER BY column tells it to rearange the results according to that column's data, and the DESC tells it to reverse the results (thus putting the last one first). After that, the LIMIT 1 tells it to only pass back one row.

Comparing results with today's date?

Not sure what your asking!

However

SELECT  GETDATE()

Will get you the current date and time

SELECT  DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Will get you just the date with time set to 00:00:00

What is difference between mutable and immutable String in java

In Java, all strings are immutable. When you are trying to modify a String, what you are really doing is creating a new one. However, when you use a StringBuilder, you are actually modifying the contents, instead of creating a new one.

What is the difference between an interface and abstract class?

The shortest way to sum it up is that an interface is:

  1. Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.
  2. Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not.
  3. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.

Meanwhile, an abstract class is:

  1. Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract.
  2. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified).
  3. Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.

Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.

That's why each element has six DOM properties for your convenience: offsetWidth, offsetHeight, clientWidth, clientHeight, scrollWidth and scrollHeight. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).

Let's go through them in detail:

  • offsetWidth, offsetHeight: The size of the visual box incuding all borders. Can be calculated by adding width/height and paddings and borders, if the element has display: block
  • clientWidth, clientHeight: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.
  • scrollWidth, scrollHeight: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.

CSS2 Box Model

Try it out: jsFiddle


Since offsetWidth takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula

scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth

Unfortunately, we may get rounding errors, since offsetWidth and clientWidth are always integers, while the actual sizes may be fractional with zoom levels other than 1.

Note that this

scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth

does not work reliably in Chrome, since Chrome returns width with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Python: Ignore 'Incorrect padding' error when base64 decoding

"Incorrect padding" can mean not only "missing padding" but also (believe it or not) "incorrect padding".

If suggested "adding padding" methods don't work, try removing some trailing bytes:

lens = len(strg)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
    result = base64.decodestring(strg[:lenx])
except etc

Update: Any fiddling around adding padding or removing possibly bad bytes from the end should be done AFTER removing any whitespace, otherwise length calculations will be upset.

It would be a good idea if you showed us a (short) sample of the data that you need to recover. Edit your question and copy/paste the result of print repr(sample).

Update 2: It is possible that the encoding has been done in an url-safe manner. If this is the case, you will be able to see minus and underscore characters in your data, and you should be able to decode it by using base64.b64decode(strg, '-_')

If you can't see minus and underscore characters in your data, but can see plus and slash characters, then you have some other problem, and may need the add-padding or remove-cruft tricks.

If you can see none of minus, underscore, plus and slash in your data, then you need to determine the two alternate characters; they'll be the ones that aren't in [A-Za-z0-9]. Then you'll need to experiment to see which order they need to be used in the 2nd arg of base64.b64decode()

Update 3: If your data is "company confidential":
(a) you should say so up front
(b) we can explore other avenues in understanding the problem, which is highly likely to be related to what characters are used instead of + and / in the encoding alphabet, or by other formatting or extraneous characters.

One such avenue would be to examine what non-"standard" characters are in your data, e.g.

from collections import defaultdict
d = defaultdict(int)
import string
s = set(string.ascii_letters + string.digits)
for c in your_data:
   if c not in s:
      d[c] += 1
print d

How to find substring from string?

As user1511510 has identified, there's an unusual case when abc is at the end of the file name. We need to look for either /abc/ or /abc followed by a string-terminator '\0'. A naive way to do this would be to check if either /abc/ or /abc\0 are substrings:

#include <stdio.h>
#include <string.h>

int main() {
    const char *str = "/user/desktop/abc";
    const int exists = strstr(str, "/abc/") || strstr(str, "/abc\0");
    printf("%d\n",exists);
    return 0;
}

but exists will be 1 even if abc is not followed by a null-terminator. This is because the string literal "/abc\0" is equivalent to "/abc". A better approach is to test if /abc is a substring, and then see if the character after this substring (indexed using the pointer returned by strstr()) is either a / or a '\0':

#include <stdio.h>
#include <string.h>

int main() {
    const char *str = "/user/desktop/abc", *substr;
    const int exists = (substr = strstr(str, "/abc")) && (substr[4] == '\0' || substr[4] == '/');
    printf("%d\n",exists);
    return 0;
}

This should work in all cases.

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

This may help somebody in future that's why adding this answer.

In my Case for android studio project. I have to enable Places API as well to get suggestions

This works for me.

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

How do you find out the caller function in JavaScript?

Try the following code:

function getStackTrace(){
  var f = arguments.callee;
  var ret = [];
  var item = {};
  var iter = 0;

  while ( f = f.caller ){
      // Initialize
    item = {
      name: f.name || null,
      args: [], // Empty array = no arguments passed
      callback: f
    };

      // Function arguments
    if ( f.arguments ){
      for ( iter = 0; iter<f.arguments.length; iter++ ){
        item.args[iter] = f.arguments[iter];
      }
    } else {
      item.args = null; // null = argument listing not supported
    }

    ret.push( item );
  }
  return ret;
}

Worked for me in Firefox-21 and Chromium-25.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

Is it possible to get the current spark context settings in PySpark?

Spark 1.6+

sc.getConf.getAll.foreach(println)

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Here is another solution you could have used. It is working in my app.

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        android.support.v7.app.ActionBar actionBar =getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);            
        setContentView(R.layout.activity_main)

Then you can get rid of that import for the one line ActionBar use.

PHP Curl UTF-8 Charset

function page_title($val){
    include(dirname(__FILE__).'/simple_html_dom.php');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$val);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $return = curl_exec($ch); 
    $encot = false;
    $charset = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    curl_close($ch); 
    $html = str_get_html('"'.$return.'"');

    if(strpos($charset,'charset=') !== false) {
        $c = str_replace("text/html; charset=","",$charset);
        $encot = true;
    }
    else {
        $lookat=$html->find('meta[http-equiv=Content-Type]',0);
        $chrst = $lookat->content;
        preg_match('/charset=(.+)/', $chrst, $found);
        $p = trim($found[1]);
        if(!empty($p) && $p != "")
        {
            $c = $p;
            $encot = true;
        }
    }
    $title = $html->find('title')[0]->innertext;
    if($encot == true && $c != 'utf-8' && $c != 'UTF-8') $title = mb_convert_encoding($title,'UTF-8',$c);

    return $title;
}

Parse json string using JSON.NET

You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:

string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";

var jss = new JavaScriptSerializer();

dynamic data = jss.Deserialize<dynamic>(json);

StringBuilder sb = new StringBuilder();

sb.Append("<table>\n  <thead>\n    <tr>\n");

// Build the header based on the keys in the
//  first data item.
foreach (string key in data["items"][0].Keys) {
        sb.AppendFormat("      <th>{0}</th>\n", key);
}

sb.Append("    </tr>\n  </thead>\n  <tbody>\n");

foreach (Dictionary<string, object> item in data["items"]) {
    sb.Append("    <tr>\n");

    foreach (string val in item.Values) {
        sb.AppendFormat("      <td>{0}</td>\n", val);
    }
}

sb.Append("    </tr>\n  </tbody>\n</table>");

string myTable = sb.ToString();

At the end, myTable will hold a string that looks like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Job</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>AAA</td>
            <td>22</td>
            <td>PPP</td>
        <tr>
            <td>BBB</td>
            <td>25</td>
            <td>QQQ</td>
        <tr>
            <td>CCC</td>
            <td>38</td>
            <td>RRR</td>
        </tr>
    </tbody>
</table>

How can I calculate the number of lines changed between two commits in Git?

If you want to check the number of insertions, deletions & commits, between two branches or commits.

using commit id's:

git log <commit-id>..<commit-id> --numstat --pretty="%H" --author="<author-name>" | awk 'NF==3 {added+=$1; deleted+=$2} NF==1 {commit++} END {printf("total lines added: +%d\ntotal lines deleted: -%d\ntotal commits: %d\n", added, deleted, commit)}'

using branches:

git log <parent-branch>..<child-branch> --numstat --pretty="%H" --author="<author-name>" | awk 'NF==3 {added+=$1; deleted+=$2} NF==1 {commit++} END {printf("total lines added: +%d\ntotal lines deleted: -%d\ntotal commits: %d\n", added, deleted, commit)}'

Keep values selected after form submission

JavaScript only solution:

var tmpParams = decodeURIComponent(window.location.search.substr(1)).split("&");
for (var i = 0; i < tmpParams.length; i++) {
    var tmparr = tmpParams[i].split("=");
    var tmp = document.getElementsByName(tmparr[0])[0];
    if (!!tmp){
        document.getElementsByName(tmparr[0])[0].value = tmparr[1];
    }
}

Or if you are using jQuery you can replace

 var tmp = document.getElementsByName(tmparr[0])[0];
 if (!!tmp){
     document.getElementsByName(tmparr[0])[0].value = tmparr[1];
 }

with:

 $('*[name="'+tmparr[0]+'"]').val(tmparr[1]);

Disable Drag and Drop on HTML elements?

This JQuery Worked for me :-

$(document).ready(function() {
  $('#con_image').on('mousedown', function(e) {
      e.preventDefault();
  });
});

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How would one write object-oriented code in C?

This has been interesting to read. I have been pondering the same question myself, and the benefits of thinking about it are this:

  • Trying to imagine how to implement OOP concepts in a non-OOP language helps me understand the strengths of the OOp language (in my case, C++). This helps give me better judgement about whether to use C or C++ for a given type of application -- where the benefits of one out-weighs the other.

  • In my browsing the web for information and opinions on this I found an author who was writing code for an embedded processor and only had a C compiler available: http://www.eetimes.com/discussion/other/4024626/Object-Oriented-C-Creating-Foundation-Classes-Part-1

In his case, analyzing and adapting OOP concepts in plain C was a valid pursuit. It appears he was open to sacrificing some OOP concepts due to the performance overhead hit resulting from attempting to implement them in C.

The lesson I've taken is, yes it can be done to a certain degree, and yes, there are some good reasons to attempt it.

In the end, the machine is twiddling stack pointer bits, making the program counter jump around and calculating memory access operations. From the efficiency standpoint, the fewer of these calculations done by your program, the better... but sometimes we have to pay this tax simply so we can organize our program in a way that makes it least susceptible to human error. The OOP language compiler strives to optimize both aspects. The programmer has to be much more careful implementing these concepts in a language like C.

HTML Entity Decode

Like Robert K said, don't use jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.

Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:

_.escape(string)

Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"

_.unescape(string)

The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, &#96; and &#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.

Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

How to create a CPU spike with a bash command

Although I'm late to the party, this post is among the top results in the google search "generate load in linux".

The result marked as solution could be used to generate a system load, i'm preferring to use sha1sum /dev/zero to impose a load on a cpu-core.

The idea is to calculate a hash sum from an infinite datastream (eg. /dev/zero, /dev/urandom, ...) this process will try to max out a cpu-core until the process is aborted. To generate a load for more cores, multiple commands can be piped together.

eg. generate a 2 core load: sha1sum /dev/zero | sha1sum /dev/zero

How to put a jpg or png image into a button in HTML

You can style the button using CSS or use an image-input. Additionally you might use the button element which supports inline content.

<button type="submit"><img src="/path/to/image" alt="Submit"></button>

SQL statement to select all rows from previous day

This should do it:

WHERE `date` = CURDATE() - INTERVAL 1 DAY

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

On Duplicate Key Update same as insert

Just in case you are able to utilize a scripting language to prepare your SQL queries, you could reuse field=value pairs by using SET instead of (a,b,c) VALUES(a,b,c).

An example with PHP:

$pairs = "a=$a,b=$b,c=$c";
$query = "INSERT INTO $table SET $pairs ON DUPLICATE KEY UPDATE $pairs";

Example table:

CREATE TABLE IF NOT EXISTS `tester` (
  `a` int(11) NOT NULL,
  `b` varchar(50) NOT NULL,
  `c` text NOT NULL,
  UNIQUE KEY `a` (`a`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

When to use a View instead of a Table?

Views can:

  • Simplify a complex table structure
  • Simplify your security model by allowing you to filter sensitive data and assign permissions in a simpler fashion
  • Allow you to change the logic and behavior without changing the output structure (the output remains the same but the underlying SELECT could change significantly)
  • Increase performance (Sql Server Indexed Views)
  • Offer specific query optimization with the view that might be difficult to glean otherwise

And you should not design tables to match views. Your base model should concern itself with efficient storage and retrieval of the data. Views are partly a tool that mitigates the complexities that arise from an efficient, normalized model by allowing you to abstract that complexity.

Also, asking "what are the advantages of using a view over a table? " is not a great comparison. You can't go without tables, but you can do without views. They each exist for a very different reason. Tables are the concrete model and Views are an abstracted, well, View.

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

How to increase the execution timeout in php?

optional : if you set config about php.ini but still can't upload

-this is php function to check error code

$error_type = [];
$error_type[0] = "There is no error";
$error_type[1] = "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
$error_type[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
$error_type[3] = "The uploaded file was only partially uploaded.";
$error_type[4] = "No file was uploaded.";
//$error_type["5"] = "";
$error_type[6] = "Missing a temporary folder. Introduced in PHP 5.0.3.";
$error_type[7] = "Failed to write file to disk. Introduced in PHP 5.1.0.";
$error_type[8] = "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.";
//------------------------------
//--> show msg error.
$status_code = $_FILES["uploadfile"]["error"];
if($status_code != 0){
    echo $error_type[$status_code];
    exit;
}

Linux command to check if a shell script is running or not

The simplest and efficient solution is :

pgrep -fl aa.sh

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

libxml install error using pip

Using cygwin 64 with Windows 8.

I have got...

pip install lxml (...)

gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -ggdb -O2 -pipe -Wimplicit-function-declaration -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/build=/usr/src/debug/python3-3.2.5-4 -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/src/Python-3.2.5=/usr/src/debug/python3-3.2.5-4 -I/usr/include/libxml2 -I/tmp/pip-build-b8ybku/lxml/src/lxml/includes -I/usr/include/python3.2m -c src/lxml/lxml.etree.c -o build/temp.cygwin-1.7.34-x86_64-3.2/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:8:22: fatal error: pyconfig.h: No such file or directory

compilation terminated.

/usr/lib/python3.2/distutils/dist.py:257: UserWarning: Unknown distribution option: 'bugtrack_url'

  warnings.warn(msg)

error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python3.2m -c "import setuptools, tokenize;__file__='/tmp/pip-build-b8ybku/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-u3vwj8-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-b8ybku/lxml

I have tried everything until I realized a new cygwin toolchain has messed up python logic. cygwin install a compiler called "realgcc" that is not a real gcc.

Solution

Install gcc. Ex:

 apt-cyg install gcc-g++

What is the default maximum heap size for Sun's JVM from Java SE 6?

With JDK, You can also use jinfo to connect to the JVM for the <PROCESS_ID> in question and get the value for MaxHeapSize:

jinfo -flag MaxHeapSize <PROCESS_ID>

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

Regular expression [Any number]

UPDATE: for your updated question

variable.match(/\[[0-9]+\]/);

Try this:

variable.match(/[0-9]+/);    // for unsigned integers
variable.match(/[-0-9]+/);   // for signed integers
variable.match(/[-.0-9]+/);  // for signed float numbers

Hope this helps!

Failed to resolve: com.google.firebase:firebase-core:9.0.0

dependencies {
    compile 'com.google.android.gms:play-services-maps:11.8.0'
    compile 'com.google.android.gms:play-services-auth:11.8.0'
    compile 'com.google.android.gms:play-services-ads:11.8.0'
    compile 'com.google.firebase:firebase-storage:11.8.0'

}
apply plugin: 'com.google.gms.google-services'


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {


        maven { url 'https://maven.fabric.io/public' }

        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.1'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

How do I load external fonts into an HTML document?

I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:

http://raphaeljs.com/

It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)

ArrayList: how does the size increase?

Lets look at this code (jdk1.8)

@Test
    public void testArraySize() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("ds");
        list.add("cx");
        list.add("cx");
        list.add("ww");
        list.add("ds");
        list.add("cx");
        list.add("cx");
        list.add("ww");
        list.add("ds");
        list.add("cx");
        list.add("last");
    }

1)Put break point on the line when "last" is inserted

2)Go to the add method of ArrayList You will see

ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;

3) Go to ensureCapacityInternal method this method call ensureExplicitCapacity

4)

private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
            return true;

In our example minCapacity is equal to 11 11-10 > 0 therefore You need grow method

5)

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

Lets describe each step:

1) oldCapacity = 10 because we didn't put this param when ArrayList was init ,therefore it will use default capacity(10)

2) int newCapacity = oldCapacity + (oldCapacity >> 1); Here newCapacity is equal to oldCapacity plus oldCapacity with right shift by one (oldCapacity is 10 this is the binary representation 00001010 moving one bit to right we will get 00000101 which is 5 in decimal therefore newCapacity is 10 + 5 = 15)

3)

if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;

For example your init capacity is 1, when you add the second element into arrayList newCapacity will be equal to 1(oldCapacity) + 0 (moved to right by one bit) = 1 In this case newCapacity is less than minCapacity and elementData(array object inside arrayList) can't hold new element therefore newCapacity is equal to minCapacity

4)

if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);

Check if array size reach MAX_ARRAY_SIZE (which is Integer.MAX - 8) Why the maximum array size of ArrayList is Integer.MAX_VALUE - 8?

5) Finally it copy old values to the newArray with length 15

Can you issue pull requests from the command line on GitHub?

Git now ships with a subcommand 'git request-pull' [-p] <start> <url> [<end>]

You can see the docs here

You may find this useful but it is not exactly the same as GitHub's feature.

How can I check the system version of Android?

Use This method:

 public static String getAndroidVersion() {
        String versionName = "";

        try {
             versionName = String.valueOf(Build.VERSION.RELEASE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

SELECT datetime(CURRENT_TIMESTAMP, 'localtime')

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

Is there a shortcut to make a block comment in Xcode?

UPDATE: Xcode 8 Update

Now with xcode 8 you can do:

? + ? + /

Note: Below method will not work in xcode version => 8

Very simple steps to add Block Comment functionality to any editor of mac OS X

  1. Open Automator
  2. Choose Services
  3. Search Run Shell Script and double click it

Add the below applescript in textarea

awk 'BEGIN{print "/*"}{print $0}END{print "*/"}'

apple script for block comment

  1. Save script as Block Comment

Add a keyboard shortcut

Open System Preference > Keyboard > Shortcuts, add new shortcut by clicking + and right the same name i.e. Block Comment as you given to applescript in the 4th step. Add your Keyboard Shortcut and click Add button.

New keyboard shortcut

Now you should be able to use block comment in Xcode or any other editor, select some text, use your shortcut key to block comment any line of code or right click, the context menu, and the name you gave to this script should show near the bottom.

Javascript Src Path

This works:

<script src="/clock.js" type="text/javascript"></script>

The leading slash means the root directory of your site. Strictly speaking, language="Javascript" has been deprecated by type="text/javascript".

Capitalization of tags and attributes is also widely discouraged.

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

Encrypt & Decrypt using PyCrypto AES 256

https://stackoverflow.com/a/21928790/11402877

compatible utf-8 encoding

def _pad(self, s):
    s = s.encode()
    res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
    return res

Java word count program

public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");


    int wordCount = 1,count=1;
 BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
            String str2 = "", str1 = "";

            while ((str1 = br.readLine()) != null) {

                    str2 += str1;

            }


    for (int i = 0; i < str2.length(); i++) 
    {
        if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 


        }

    System.out.println("Word count is = " +(wordCount));
}

}

AngularJS custom filter function

You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.

template:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

scope:

$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return item.name === criteria.name;
  };
};

Sanitizing strings to make them URL and filename safe?

This is a nice way to secure an upload filename:

$file_name = trim(basename(stripslashes($name)), ".\x00..\x20");

How to print third column to last column?

awk '{for (i=4; i<=NF; i++)printf("%c", $i); printf("\n");}'

prints records starting from the 4th field to the last field in the same order they were in the original file

how to make negative numbers into positive

Use float fabsf (float n) for float values.

Use double fabs (double n) for double values.

Use long double fabsl(long double) for long double values.

Use abs(int) for int values.

Copying HTML code in Google Chrome's inspect element

Do the following:

  1. Select the top most element, you want to copy. (To copy all, select <html>)
  2. Right click.
  3. Select Edit as HTML
  4. New sub-window opens up with the HTML text.
  5. This is your chance. Press CTRL+A/CTRL+C and copy the entire text field to a different window.

This is a hacky way, but it's the easiest way to do this.

How to declare an array of strings in C++?

You can use Will Dean's suggestion [#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.

The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[]) is really some_function(string *parameter).

Android Studio was unable to find a valid Jvm (Related to MAC OS)

I am using Mac OS X 10.10 also. And to fix this problem.

  1. Open Android Studio application package content (by right click on Android Studio icon in Application folder)
  2. Open file Infor.plist
  3. Search and replace:

    <key> JVM version</key>
    <string>1.6*</string>
    

replaced by:

    <key> JVM version</key>
    <string>1.6+</string>

That's it!