Programs & Examples On #Svndump

How do I define global variables in CoffeeScript?

If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()

As in,

(->@)().im_a_terrible_programmer = yes
console.log im_a_terrible_programmer

This works, because when invoking a Reference to a Function ‘bare’ (that is, func(), instead of new func() or obj.func()), something commonly referred to as the ‘function-call invocation pattern’, always binds this to the global object for that execution context.

The CoffeeScript above simply compiles to (function(){ return this })(); so we're exercising that behavior to reliably access the global object.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

From the jQuery documentation: you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}

How to get the width of a react element

Actually, would be better to isolate this resize logic in a custom hook. You can create a custom hook like this:

const useResize = (myRef) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  useEffect(() => {
    const handleResize = () => {
      setWidth(myRef.current.offsetWidth)
      setHeight(myRef.current.offsetHeight)
    }

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [myRef])

  return { width, height }
}

and then you can use it like:

const MyComponent = () => {
  const componentRef = useRef()
  const { width, height } = useResize(componentRef)

  return (
    <div ref={myRef}>
      <p>width: {width}px</p>
      <p>height: {height}px</p>
    <div/>
  )
}

How many bits is a "word"?

The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":

A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.

Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.

SQL Server: how to select records with specific date from datetime column

SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';

This will select all the data between the 2 dates

How to run a cronjob every X minutes?

If you want to run a cron every n minutes, there are a few possible options depending on the value of n.

n divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)

Here, the solution is straightforward by making use of the / notation:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
m-59/n  *  *  *  *   command

In the above, n represents the value n and m represents a value smaller than n or *. This will execute the command at the minutes m,m+n,m+2n,...

n does NOT divide 60

If n does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n minutes later.

% date -d '2015-10-21 07:28:00' +%s 
1445412480

For a cronjob to run every 42nd minute after `2015-10-21 07:28:00', the crontab would look like this:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
  *  *  *  *  *   minutetestcmd "2015-10-21 07:28:00" 42 && command

with minutetestcmd defined as

#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))

Remark: UNIX time is not influenced by leap seconds

Remark: cron has no sub-second accuracy

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

orphan removal has the same effect as ON DELETE CASCADE in the following scenario:- Lets say we have a simple many to one relationship between student entity and a guide entity, where many students can be mapped to the same guide and in database we have a foreign key relation between Student and Guide table such that student table has id_guide as FK.

    @Entity
    @Table(name = "student", catalog = "helloworld")
    public class Student implements java.io.Serializable {
     @Id
     @GeneratedValue(strategy = IDENTITY)
     @Column(name = "id")
     private Integer id;

    @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    @JoinColumn(name = "id_guide")
    private Guide guide;

// The parent entity

    @Entity
    @Table(name = "guide", catalog = "helloworld")
    public class Guide implements java.io.Serializable {

/**
 * 
 */
private static final long serialVersionUID = 9017118664546491038L;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;

@Column(name = "name", length = 45)
private String name;

@Column(name = "salary", length = 45)
private String salary;


 @OneToMany(mappedBy = "guide", orphanRemoval=true) 
 private Set<Student> students = new  HashSet<Student>(0);

In this scenario, the relationship is such that student entity is the owner of the relationship and as such we need to save the student entity in order to persist the whole object graph e.g.

    Guide guide = new Guide("John", "$1500");
    Student s1 = new Student(guide, "Roy","ECE");
    Student s2 = new Student(guide, "Nick", "ECE");
    em.persist(s1);
    em.persist(s2);

Here we are mapping the same guide with two different student objects and since the CASCADE.PERSIST is used , the object graph will be saved as below in the database table(MySql in my case)

STUDENT table:-

ID Name Dept Id_Guide

1     Roy     ECE    1

2    Nick    ECE    1

GUIDE Table:-

ID NAME Salary

1    John     $1500

and Now if I want to remove one of the students, using

      Student student1 = em.find(Student.class,1);
      em.remove(student1);

and when a student record is removed the corresponding guide record should also be removed, that's where CASCADE.REMOVE attribute in the Student entity comes into picture and what it does is ;it removes the student with identifier 1 as well the corresponding guide object(identifier 1). But in this example, there is one more student object which is mapped to the same guide record and unless we use the orphanRemoval=true attribute in the Guide Entity , the remove code above will not work.

How can I increase the cursor speed in terminal?

System Preferences => Keyboard => Key Repeat Rate

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How do I scroll the UIScrollView when the keyboard appears?

For this stuff no need to lot's of coding it's very easy like below code:-

your all textfiled in UIScrollview from nib like this image:-

enter image description here

YourViewController.h

@interface cntrInquiryViewController : UIViewController<UIScrollViewDelegate,UITextFieldDelegate>
{
     IBOutlet UITextField *txtName;
     IBOutlet UITextField *txtEmail;
     IBOutlet UIScrollView *srcScrollView;
}
@end

connect IBOutlet from nib and also Connect each delegate of UItextfiled and scrollview delegate from NIB

-(void)viewWillAppear:(BOOL)animated
{
    srcScrollView.contentSize = CGSizeMake(320, 500);

    [super viewWillAppear:YES];
}


-(void)textFieldDidBeginEditing:(FMTextField *)textField
{
    [srcScrollView setContentOffset:CGPointMake(0,textField.center.y-140) animated:YES];//you can set your  y cordinate as your req also
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
     [textField resignFirstResponder];
     [srcScrollView setContentOffset:CGPointMake(0,0) animated:YES];


    return YES;
}

NOTE if Text-filed delegate not connected then no one method working please insure that all iBOulate and delegate connected correctly

excel plot against a date time x series

[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx

Algorithm to return all combinations of k elements from n

Here is a simple JS solution:

_x000D_
_x000D_
function getAllCombinations(n, k, f1) {_x000D_
 indexes = Array(k);_x000D_
  for (let i =0; i< k; i++) {_x000D_
   indexes[i] = i;_x000D_
  }_x000D_
  var total = 1;_x000D_
  f1(indexes);_x000D_
  while (indexes[0] !== n-k) {_x000D_
   total++;_x000D_
  getNext(n, indexes);_x000D_
    f1(indexes);_x000D_
  }_x000D_
  return {total};_x000D_
}_x000D_
_x000D_
function getNext(n, vec) {_x000D_
 const k = vec.length;_x000D_
  vec[k-1]++;_x000D_
 for (var i=0; i<k; i++) {_x000D_
   var currentIndex = k-i-1;_x000D_
    if (vec[currentIndex] === n - i) {_x000D_
    var nextIndex = k-i-2;_x000D_
      vec[nextIndex]++;_x000D_
      vec[currentIndex] = vec[nextIndex] + 1;_x000D_
    }_x000D_
  }_x000D_
_x000D_
 for (var i=1; i<k; i++) {_x000D_
    if (vec[i] === n - (k-i - 1)) {_x000D_
      vec[i] = vec[i-1] + 1;_x000D_
    }_x000D_
  }_x000D_
 return vec;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
let start = new Date();_x000D_
let result = getAllCombinations(10, 3, indexes => console.log(indexes)); _x000D_
let runTime = new Date() - start; _x000D_
_x000D_
console.log({_x000D_
result, runTime_x000D_
});
_x000D_
_x000D_
_x000D_

MongoDB Aggregation: How to get total records count?

You can use toArray function and then get its length for total records count.

db.CollectionName.aggregate([....]).toArray().length

Remove the last three characters from a string

Remove the last characters from a string

TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)

.Text.Remove(10)// used to remove text starting from index 10 to end

Why does SSL handshake give 'Could not generate DH keypair' exception?

I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

with enabled debug by -Djavax.net.debug=all there was a message in a log

Could not generate DH keypair

I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jar and registering a provider in a map service class

public class MapService {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public GeocodeResult geocode() {

    }

}

A provider is registered at the first usage of MapService.

HintPath vs ReferencePath in Visual Studio

Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:

https://msdn.microsoft.com/en-us/library/ee817675.aspx#tdlg_ch4_includeoutersystemassemblieswithprojects

Excerpt:

To include and then reference an outer-system assembly
1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item.
2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control).
3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.

How to count duplicate value in an array in javascript

public class CalculateCount {
public static void main(String[] args) {
    int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
    Arrays.sort(a);
    int count=1;
    int i;
    for(i=0;i<a.length-1;i++){
        if(a[i]!=a[i+1]){
            System.out.println("The Number "+a[i]+" appears "+count+" times");
            count=1;                
        }
        else{
            count++;
        }
    }
    System.out.println("The Number "+a[i]+" appears "+count+" times");

}   

}

How to get the indexpath.row when an element is activated?

After seeing Paulw11's suggestion of using a delegate callback, I wanted to elaborate on it slightly/put forward another, similar suggestion. Should you not want to use the delegate pattern you can utilise closures in swift as follows:

Your cell class:

class Cell: UITableViewCell {
    @IBOutlet var button: UIButton!

    var buttonAction: ((sender: AnyObject) -> Void)?

    @IBAction func buttonPressed(sender: AnyObject) {
        self.buttonAction?(sender)
    }
}

Your cellForRowAtIndexPath method:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
    cell.buttonAction = { (sender) in
        // Do whatever you want from your button here.
    }
    // OR
    cell.buttonAction = buttonPressed // <- Method on the view controller to handle button presses.
}

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

Replace new lines with a comma delimiter with Notepad++?

For Notepad++ 5.9

  1. Press Ctrl+H
  2. Select Search mode Extended(\n, \r, \t, \o, \x...)
  3. Enter Find what: \r\n
  4. Enter Replace with: ,
  5. Replace_All should get the required result.

Is the size of C "int" 2 bytes or 4 bytes?

The only guarantees are that char must be at least 8 bits wide, short and int must be at least 16 bits wide, and long must be at least 32 bits wide, and that sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) (same is true for the unsigned versions of those types).

int may be anywhere from 16 to 64 bits wide depending on the platform.

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv

How do I get the list of keys in a Dictionary?

To get list of all keys

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();

System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

Visual Studio Does not recognize System.Linq

System.Linq Namespace

How do I use installed packages in PyCharm?

Download anaconda https://anaconda.org/

once done installing anaconda...

Go into Settings -> Project Settings -> Project Interpreter.

Then navigate to the "Paths" tab and search for /anaconda/bin/python

click apply

enter image description here

How to Get enum item name from its value

You can't directly, enum in C++ are not like Java enums.

The usual approach is to create a std::map<WeekEnum,std::string>.

std::map<WeekEnum,std::string> m;
m[Mon] = "Monday";
//...
m[Sun] = "Sunday";

iPhone/iOS JSON parsing tutorial

This is the tutorial I used to get to darrinm's answer. It's updated for ios5/6 and really easy. When I'm popular enough I'll delete this and add it as a comment to his answer.

http://www.raywenderlich.com/5492/working-with-json-in-ios-5

http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/

How to install pip in CentOS 7?

The CentOS 7 yum package for python34 does include the ensurepip module, but for some reason is missing the setuptools and pip files that should be a part of that module. To fix, download the latest wheels from PyPI into the module's _bundled directory (/lib64/python3.4/ensurepip/_bundled/):

setuptools-18.4-py2.py3-none-any.whl
pip-7.1.2-py2.py3-none-any.whl

then edit __init__.py to match the downloaded versions:

_SETUPTOOLS_VERSION = "18.4"
_PIP_VERSION = "7.1.2"

after which python3.4 -m ensurepip works as intended. Ensurepip is invoked automatically every time you create a virtual environment, for example:

pyvenv-3.4 py3
source py3/bin/activate

Hopefully RH will fix the broken Python3.4 yum package so that manual patching isn't needed.

Multiple parameters in a List. How to create without a class?

Another solution create generic list of anonymous type.

 var list = new[]
 { 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
 }.ToList();

 foreach (var item in list)
 {
    Console.WriteLine(item.Name);
 }

This also gives you intellisense support, I think in some situations its better than Tuple and Dictionary.

Should methods in a Java interface be declared with or without a public access modifier?

It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.

It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to handle anchor hash linking in AngularJS

I got around this in the route logic for my app.

function config($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: '/partials/search.html',
      controller: 'ctrlMain'
    })
    .otherwise({
      // Angular interferes with anchor links, so this function preserves the
      // requested hash while still invoking the default route.
      redirectTo: function() {
        // Strips the leading '#/' from the current hash value.
        var hash = '#' + window.location.hash.replace(/^#\//g, '');
        window.location.hash = hash;
        return '/' + hash;
      }
    });
}

How can I get the count of line in a file in an efficient way?

All previous answers suggest to read though the whole file and count the amount of newlines you find while doing this. You commented some as "not effective" but thats the only way you can do that. A "line" is nothing else as a simple character inside the file. And to count that character you must have a look at every single character within the file.

I'm sorry, but you have no choice. :-)

How should I call 3 functions in order to execute them one after the other?

In Javascript, there are synchronous and asynchronous functions.

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.

Asynchronous Functions

Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.

But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.

Callbacks

Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.

Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.

If we create the functions like this

function some_3secs_function(value, callback){
  //do stuff
  callback();
}

then you can call then in order, like this:

some_3secs_function(some_value, function() {
  some_5secs_function(other_value, function() {
    some_8secs_function(third_value, function() {
      //All three functions have completed, in order.
    });
  });
});

Timeouts

In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.

function executeAsynchronously(functions, timeout) {
  for(var i = 0; i < functions.length; i++) {
    setTimeout(functions[i], timeout);
  }
}

This can be called like so:

executeAsynchronously(
    [doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

JUnit Eclipse Plugin?

Eclipse has built in JUnit functionality. Open your Run Configuration manager to create a test to run. You can also create JUnit Test Cases/Suites from New->Other.

Using jquery to delete all elements with a given id

The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().

var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove(); 

The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById ("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

How to increment datetime by custom months in python without using library

Simplest solution is to go at the end of the month (we always know that months have at least 28 days) and add enough days to move to the next moth:

>>> from datetime import datetime, timedelta
>>> today = datetime.today()
>>> today
datetime.datetime(2014, 4, 30, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2014, 5, 30, 11, 47, 27, 811253)

Also works between years:

>>> dec31
datetime.datetime(2015, 12, 31, 11, 47, 27, 811253)
>>> today = dec31
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)

Just keep in mind that it is not guaranteed that the next month will have the same day, for example when moving from 31 Jan to 31 Feb it will fail:

>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

So this is a valid solution if you need to move to the first day of the next month, as you always know that the next month has day 1 (.replace(day=1)). Otherwise, to move to the last available day, you might want to use:

>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> next_month = (today.replace(day=28) + timedelta(days=10))
>>> import calendar
>>> next_month.replace(day=min(today.day, 
                               calendar.monthrange(next_month.year, next_month.month)[1]))
datetime.datetime(2016, 2, 29, 11, 47, 27, 811253)

How to make <input type="file"/> accept only these types?

Use Like below

<input type="file" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf" />

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

Angular 2 Hover event

For handling the event on overing, you can try something like this (it works for me):

In the Html template:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

In the angular component:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

What is a practical, real world example of the Linked List?

In the .NET BCL, the class System.Exception has a property called InnerException, which points to another exception or else is null. This forms a linked list.

In System.Type, the BaseType property points to another type in the same way.

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

accepting HTTPS connections with self-signed certificates

Google recommends the usage of Android Volley for HTTP/HTTPS connections, since that HttpClient is deprecated. So, you know the right choice :).

And also, NEVER NUKE SSL Certificates (NEVER!!!).

To nuke SSL Certificates, is totally against the purpose of SSL, which is promoting security. There's no sense of using SSL, if you're planning to bomb all SSL certificates that comes. A better solution would be creating a custom TrustManager on your App + using Android Volley for HTTP/HTTPS connections.

Here's a Gist which I created, with a basic LoginApp, performing HTTPS connections, using a Self-Signed Certificate on the server-side, accepted on the App.

Here's also another Gist that may help, for creating Self-Signed SSL Certificates for setting up on your Server and also using the certificate on your App. Very important: you must copy the .crt file which was generated by the script above, to the "raw" directory from your Android project.

What is the most effective way for float and double comparison?

I'd be very wary of any of these answers that involves floating point subtraction (e.g., fabs(a-b) < epsilon). First, the floating point numbers become more sparse at greater magnitudes and at high enough magnitudes where the spacing is greater than epsilon, you might as well just be doing a == b. Second, subtracting two very close floating point numbers (as these will tend to be, given that you're looking for near equality) is exactly how you get catastrophic cancellation.

While not portable, I think grom's answer does the best job of avoiding these issues.

Twitter Bootstrap modal: How to remove Slide down effect

I have found the best solution that removes the slide but leaves the fade is by adding the following css in a css file of your chosing which is invoked after the bootstrap.css

.modal.fade .modal-dialog 
{
    -moz-transition: none !important;
    -o-transition: none !important;
    -webkit-transition: none !important;
    transition: none !important;

    -moz-transform: none !important;
    -ms-transform: none !important;
    -o-transform: none !important;
    -webkit-transform: none !important;
    transform: none !important;
}

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

tmux set -g mouse-mode on doesn't work

Paste here in ~/.tmux.conf

set -g mouse on

and run on terminal

tmux source-file ~/.tmux.conf

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Giving my function access to outside variable

$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

Making HTTP Requests using Chrome Developer tools

If your web page has jquery in your page, then you can do it writing on chrome developers console:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Its jquery way of doing it!

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

How to call Oracle MD5 hash function?

In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.

select standard_hash('foo', 'MD5') from dual;

The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:

select rawtohex(
    DBMS_CRYPTO.Hash (
        UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
        2)
    ) from dual;

Output:

ACBD18DB4CC2F85CEDEF654FCCC4A4D8

Add a lower function call if needed. More on DBMS_CRYPTO.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

One line solution:

& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You will need to repeat your call to strtol inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...); instead of while, you don't get a the same sort of repeat things twice behaviour.

You should also format your code so that it's possible to see where the code is inside a loop and not.

What is the proper REST response code for a valid request but an empty data?

It is sad that something so simple and well defined became "opinion based" in this thread.

A HTTP server only knows of "entities", which is an abstraction for any content, be it a static web page, a list of search results, a list of other entities, a json description of something, a media file, etc etc.

Each such entity is expected to be identifiable by a unique URL, e.g.

  • /user/9 -- a single entity: a USER ID=9
  • /users -- a single entity: a LIST of all users
  • /media/x.mp3 -- a single entity: a media FILE called x.mp3
  • /search -- a single entity: a dynamic CONTENT based on query params

If a server finds a resource by the given URL, it does not matter what its contents are -- 2G of data, null, {}, [] -- as long as it exists, it will be 200. But if such entity is not known to the server, it is EXPECTED to return 404 "Not Found".

One confusion seems to be from developers who think if the application has a handler for a certain path shape, it should not be an error. In the eyes of the HTTP protocol it does not matter what happened in the internals of the server (ie. whether the default router responded or a handler for a specific path shape), as long as there is no matching entity on the server to the requested URL (that requested MP3 file, webpage, user object etc), which would return valid contents (empty or otherwise), it must be 404 (or 410 etc).

Another point of confusion seems to be around "no data" and "no entity". The former is about content of an entity, and the latter about its existence.

Example 1:

  • No data: /users returns 200 OK, body: [] because nobody registered yet
  • No entity: /users returns 404 because there is no path /users

Example 2:

  • No data: /user/9 returns return 200 OK, body: {}, because user ID=9 never entered his/her personal data
  • No entity: /user/9 returns 404 because there is no user ID=9

Example 3:

  • No data: /search?name=Joe returns 200 OK [], because there are no Joe's in the DB
  • No entity: /search?name=Joe returns 404 because there is no path /search

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

JAXB Exception: Class not known to this context

Your ProfileDto class is not referenced in SearchResultDto. Try adding @XmlSeeAlso(ProfileDto.class) to SearchResultDto.

Create space at the beginning of a UITextField

To Extend original answer for leftView and Swift5+

class TextField: UITextField {

let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding)
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding)
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect;
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding);
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect;
}

func adjustRectOriginForLeftView(bounds : CGRect) -> CGRect{
    var paddedRect = bounds;
    paddedRect.origin.x += self.leftView!.frame.width
    return paddedRect
    
}

}

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.

But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

int k = 100; Integer it1 = new Integer(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();

System.out.println(m*m); // prints 10000

//intValue() is a method of Integer class that returns an int data type.

Generate random numbers following a normal distribution in C/C++

This is how you generate the samples on a modern C++ compiler.

#include <random>
...
std::mt19937 generator;
double mean = 0.0;
double stddev  = 1.0;
std::normal_distribution<double> normal(mean, stddev);
cerr << "Normal: " << normal(generator) << endl;

Display Python datetime without time

You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].

You can pass this as map/apply to use it in a dataframe/series too.

Two column div layout with fluid left and fixed right column

I think this is a simple answer , this will split child devs 50% each based on the parent width.

 <div style="width: 100%">
        <div style="width: 50%; float: left; display: inline-block;">
            Hello world
        </div>
        <div style="width: 50%; display: inline-block;">
            Hello world
        </div>
    </div>

Using the HTML5 "required" attribute for a group of checkboxes?

Really simple way to verify if at least one checkbox is checked:

function isAtLeastOneChecked(name) {
    let checkboxes = Array.from(document.getElementsByName(name));
    return checkboxes.some(e => e.checked);
}

Then you can implement whatever logic you want to display an error.

Get JSON Data from URL Using Android?

private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        if (urls.length > 0) {
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("x-li-format", "json");
            try {
                HttpResponse response = httpClient.execute(httpget);
                if (response != null) {
                    //If status is OK 200
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        return new JSONObject(result);
                    }
                }
            } catch (IOException e) {

            } catch (JSONException e) {
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject data) {
        if (data != null) {
            Log.d(TAG, String.valueOf(data));
        }
    }

}

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

What is the Sign Off feature in Git for?

Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.

It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.

Failed to run sdkmanager --list with Java 9

As we read in the previous comments this error is occurring because the current SDK version is incompatible with the newest Java versions: 9 and 10.

So, to solve it, you can downgrade your java version to Java 8, or as a workaround, you can export the following option on your terminal:

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

If this does not work try to exports the java.xml.bind instead.

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

This will solve this error for the sdkmanager

And to make it saved permanently you can export the JAVA_OPTS in your profile file on Linux (.zshrc, .bashrc and etc.) or add it as an environment variable permanently on Windows.


ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.

Ref: JDK 11: End of the road for Java EE modules

How to verify Facebook access token?

Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token in:

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app-token-or-admin-token}

However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app_id}|{app_secret}

As described in Facebook's documentation for Access Tokens here.

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

RegEx for valid international mobile phone number

// Regex - Check Singapore valid mobile numbers

public static boolean isSingaporeMobileNo(String str) {
    Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
    Matcher matcher = mobNO.matcher(str);
    if (matcher.find()) {
        return true;
    } else {
        return false;
    }
}

SQL Server Express CREATE DATABASE permission denied in database 'master'

What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.

git diff between cloned and original remote repository

1) Add any remote repositories you want to compare:

git remote add foobar git://github.com/user/foobar.git

2) Update your local copy of a remote:

git fetch foobar

Fetch won't change your working copy.

3) Compare any branch from your local repository to any remote you've added:

git diff master foobar/master

GET URL parameter in PHP

As Alvaro said, $_GET is not a function but an array containing the parameters So you can retrieve one element from that array using

<?php
$link = $_GET['link'];
echo $link;
?>

Expected OP:

www.google.com

Detect iPad users using jQuery?

Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone and isiPad to be true for users visiting your site on their iPad from the Facebook app.

The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.

Compare these user agent strings from iOS devices:

# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]

Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.

The old way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);

If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!

The correct way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
  IS_IPHONE = false;
}

We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.

Using a Python subprocess call to invoke a Python script

subprocess.call expects the same arguments as subprocess.Popen - that is a list of strings (the argv in C) rather than a single string.

It's quite possible that your child process attempted to run "s" with the parameters "o", "m", "e", ...

Docker container will automatically stop after "docker run -d"

Background

A Docker container runs a process (the "command" or "entrypoint") that keeps it alive. The container will continue to run as long as the command continues to run.

In your case, the command (/bin/bash, by default, on centos:latest) is exiting immediately (as bash does when it's not connected to a terminal and has nothing to run).

Normally, when you run a container in daemon mode (with -d), the container is running some sort of daemon process (like httpd). In this case, as long as the httpd daemon is running, the container will remain alive.

What you appear to be trying to do is to keep the container alive without a daemon process running inside the container. This is somewhat strange (because the container isn't doing anything useful until you interact with it, perhaps with docker exec), but there are certain cases where it might make sense to do something like this.

(Did you mean to get to a bash prompt inside the container? That's easy! docker run -it centos:latest)

Solution

A simple way to keep a container alive in daemon mode indefinitely is to run sleep infinity as the container's command. This does not rely doing strange things like allocating a TTY in daemon mode. Although it does rely on doing strange things like using sleep as your primary command.

$ docker run -d centos:latest sleep infinity
$ docker ps
CONTAINER ID  IMAGE         COMMAND          CREATED       STATUS       PORTS NAMES
d651c7a9e0ad  centos:latest "sleep infinity" 2 seconds ago Up 2 seconds       nervous_visvesvaraya

Alternative Solution

As indicated by cjsimon, the -t option allocates a "pseudo-tty". This tricks bash into continuing to run indefinitely because it thinks it is connected to an interactive TTY (even though you have no way to interact with that particular TTY if you don't pass -i). Anyway, this should do the trick too:

$ docker run -t -d centos:latest

Not 100% sure whether -t will produce other weird interactions; maybe leave a comment below if it does.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Find provisioning profile in Xcode 5

xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".

Connecting to a network folder with username/password in Powershell

This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:

net use \\server\share /user:<domain\username> <password>

And then do whatever you need to do in PowerShell...

How to indent a few lines in Markdown markup?

What about place a determined space in the start of paragraph using the math environment as like:

$\qquad$ My line of text ...

This works for me and hope work for you too.

selenium - chromedriver executable needs to be in PATH

An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.

Change USER_NAME and FOLDER in accordance to your computer.

For Windows

driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")

For Linux/Mac

driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")

Reference jars inside a jar

Default implementations of the classloader cannot load from a jar-within-a-jar: in order to do so, the entire 'sub-jar' would have to be loaded into memory, which defeats the random-access benefits of the jar format (reference pending - I'll make an edit once I find the documentation supporting this).

I recommend using a program such as JarSplice to bundle everything for you into one clean executable jar.

Edit: Couldn't find the source reference, but here's an un-resolved RFE off the Sun website describing this exact 'problem': http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4648386

Also, you could 'test' that your program works by placing the library jar files in a \lib sub-directory of your classes directory, then running from the command line. In other words, with the following directory structure:

classes/org/sai/com/DerbyDemo.class
classes/org/sai/com/OtherClassFiles.class
classes/lib/derby.jar
classes/lib/derbyclient.jar

From the command line, navigate to the above-mentioned 'classes' directory, and type:

java -cp .:lib/* org.sai.com.DerbyDemo

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

Just in case of someone has the same problem. I'am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8", the problem is gone.

How do I parse a HTML page with Node.js

Use Cheerio. It isn't as strict as jsdom and is optimized for scraping. As a bonus, uses the jQuery selectors you already know.

? Familiar syntax: Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.

? Blazingly fast: Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.

? Insanely flexible: Cheerio wraps around @FB55's forgiving htmlparser. Cheerio can parse nearly any HTML or XML document.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Your syntax almost works in SQL Server 2008 (but not in SQL Server 20051):

CREATE TABLE MyTable (id int, name char(10));

INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');

SELECT * FROM MyTable;

id |  name
---+---------
1  |  Bob       
2  |  Peter     
3  |  Joe       

1 When the question was answered, it was not made evident that the question was referring to SQL Server 2005. I am leaving this answer here, since I believe it is still relevant.

How do you cast a List of supertypes to a List of subtypes?

The best safe way is to implement an AbstractList and cast items in implementation. I created ListUtil helper class:

public class ListUtil
{
    public static <TCastTo, TCastFrom extends TCastTo> List<TCastTo> convert(final List<TCastFrom> list)
    {
        return new AbstractList<TCastTo>() {
            @Override
            public TCastTo get(int i)
            {
                return list.get(i);
            }

            @Override
            public int size()
            {
                return list.size();
            }
        };
    }

    public static <TCastTo, TCastFrom> List<TCastTo> cast(final List<TCastFrom> list)
    {
        return new AbstractList<TCastTo>() {
            @Override
            public TCastTo get(int i)
            {
                return (TCastTo)list.get(i);
            }

            @Override
            public int size()
            {
                return list.size();
            }
        };
    }
}

You can use cast method to blindly cast objects in list and convert method for safe casting. Example:

void test(List<TestA> listA, List<TestB> listB)
{
    List<TestB> castedB = ListUtil.cast(listA); // all items are blindly casted
    List<TestB> convertedB = ListUtil.<TestB, TestA>convert(listA); // wrong cause TestA does not extend TestB
    List<TestA> convertedA = ListUtil.<TestA, TestB>convert(listB); // OK all items are safely casted
}

How do I combine a background-image and CSS3 gradient on the same element?

I always use the following code to make it work. There are some notes:

  1. If you place image URL before gradient, this image will be displayed above the gradient as expected.

_x000D_
_x000D_
.background-gradient {_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
_x000D_
_x000D_

  1. If you place gradient before image URL, this image will be displayed under the gradient.

_x000D_
_x000D_
.background-gradient {_x000D_
  background: -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -webkit-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  width: 500px;_x000D_
  height: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
_x000D_
_x000D_

This technique is just the same as we have multiple background images as describe here

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

String Array object in Java

I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.

public class Athlete {

private String name;
private String city;

public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){} 
}




public class Main{
public static void main (String [] args){

String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord

--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);

}
}

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

HTTP Content-Type Header and JSON

Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

Differences between Lodash and Underscore.js

They are pretty similar, with Lodash is taking over...

They both are a utility library which takes the world of utility in JavaScript...

It seems Lodash is getting updated more regularly now, so more used in the latest projects...

Also Lodash seems is lighter by a couple of KBs...

Both have a good API and documentation, but I think the Lodash one is better...

Here is a screenshot for each of the documentation items for getting the first value of an array...

Underscore.js:

Underscore.js

Lodash:

Lodash

As things may get updated time to time, just check their website also...

Lodash

Underscore.js

Can pm2 run an 'npm start' script

I needed to run a specific npm script on my app in pm2 (for each env) In my case, it was when I created a staging/test service

The command that worked for me (the args must be forwarded that way):

pm2 start npm --name "my-app-name" -- run "npm:script"

examples:

pm2 start npm --name "myApp" -- run "start:test"

pm2 start npm --name "myApp" -- run "start:staging"

pm2 start npm --name "myApp" -- run "start:production"

Hope it helped

Javascript: Fetch DELETE and PUT requests

Here is a fetch POST example. You can do the same for DELETE.

function createNewProfile(profile) {
    const formData = new FormData();
    formData.append('first_name', profile.firstName);
    formData.append('last_name', profile.lastName);
    formData.append('email', profile.email);

    return fetch('http://example.com/api/v1/registration', {
        method: 'POST',
        body: formData
    }).then(response => response.json())
}

createNewProfile(profile)
   .then((json) => {
       // handle success
    })
   .catch(error => error);

Serialize an object to string

[VB]

Public Function XmlSerializeObject(ByVal obj As Object) As String

    Dim xmlStr As String = String.Empty

    Dim settings As New XmlWriterSettings()
    settings.Indent = False
    settings.OmitXmlDeclaration = True
    settings.NewLineChars = String.Empty
    settings.NewLineHandling = NewLineHandling.None

    Using stringWriter As New StringWriter()
        Using xmlWriter__1 As XmlWriter = XmlWriter.Create(stringWriter, settings)

            Dim serializer As New XmlSerializer(obj.[GetType]())
            serializer.Serialize(xmlWriter__1, obj)

            xmlStr = stringWriter.ToString()
            xmlWriter__1.Close()
        End Using

        stringWriter.Close()
    End Using

    Return xmlStr.ToString
End Function

Public Function XmlDeserializeObject(ByVal data As [String], ByVal objType As Type) As Object

    Dim xmlSer As New System.Xml.Serialization.XmlSerializer(objType)
    Dim reader As TextReader = New StringReader(data)

    Dim obj As New Object
    obj = DirectCast(xmlSer.Deserialize(reader), Object)
    Return obj
End Function

[C#]

public string XmlSerializeObject(object obj)
{
    string xmlStr = String.Empty;
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.OmitXmlDeclaration = true;
    settings.NewLineChars = String.Empty;
    settings.NewLineHandling = NewLineHandling.None;

    using (StringWriter stringWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            XmlSerializer serializer = new XmlSerializer( obj.GetType());
            serializer.Serialize(xmlWriter, obj);
            xmlStr = stringWriter.ToString();
            xmlWriter.Close();
        }
    }
    return xmlStr.ToString(); 
}

public object XmlDeserializeObject(string data, Type objType)
{
    XmlSerializer xmlSer = new XmlSerializer(objType);
    StringReader reader = new StringReader(data);

    object obj = new object();
    obj = (object)(xmlSer.Deserialize(reader));
    return obj;
}

What are ABAP and SAP?

SAP is really a big Company that offers incredible solutions oriented to medium-large companies.

Actually, I can say that the main IT products are: ERP, WEB, Human Resources, Integration, BI, Reports, Machine Learning, Mobile, Cloud, Robotics, and so on.

On the cloud, you can even find solutions using Cloud Foundry, NodeJS, HTML5, Java, etc.

It's really huge the solutions that offers to their customers.

What's the best way to break from nested loops in JavaScript?

I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".

Close to the OP's solution:

    Args.forEach(function (arg) {
        // This guard is not necessary,
        // since writing an empty string to document would not change it.
        if (!getAnchorTag(arg))
            return;

        document.write(getAnchorTag(arg));
    });

    function getAnchorTag (name) {
        var res = '';

        Object.keys(Navigation.Headings).some(function (Heading) {
            return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
                if (name == Navigation.Headings[Heading][Item].Name) {
                    res = ("<a href=\""
                                 + Navigation.Headings[Heading][Item].URL + "\">"
                                 + Navigation.Headings[Heading][Item].Name + "</a> : ");
                    return true;
                }
            });
        });

        return res;
    }

Solution that reduces iterating over the Headings/Items:

    var remainingArgs = Args.slice(0);

    Object.keys(Navigation.Headings).some(function (Heading) {
        return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
            var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);

            if (i === -1)
                return;

            document.write("<a href=\""
                                         + Navigation.Headings[Heading][Item].URL + "\">"
                                         + Navigation.Headings[Heading][Item].Name + "</a> : ");
            remainingArgs.splice(i, 1);

            if (remainingArgs.length === 0)
                return true;
            }
        });
    });

Call method when home button pressed

I also struggled with HOME button for awhile. I wanted to stop/skip a background service (which polls location) when user clicks HOME button.

here is what I implemented as "hack-like" solution;

keep the state of the app on SharedPreferences using boolean value

on each activity

onResume() -> set appactive=true

onPause() -> set appactive=false

and the background service checks the appstate in each loop, skips the action

IF appactive=false

it works well for me, at least not draining the battery anymore, hope this helps....

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

is there a require for json in node.js

You can import json files by using the node.js v14 experimental json modules flag. More details here

file.js

import data from './folder/file.json'

export default {
  foo () {
    console.log(data)
  }
}

And you call it with node --experimental-json-modules file.js

Make xargs execute the command once for each line of input

If you want to run the command for every line (i.e. result) coming from find, then what do you need the xargs for?

Try:

find path -type f -exec your-command {} \;

where the literal {} gets substituted by the filename and the literal \; is needed for find to know that the custom command ends there.

EDIT:

(after the edit of your question clarifying that you know about -exec)

From man xargs:

-L max-lines
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x.

Note that filenames ending in blanks would cause you trouble if you use xargs:

$ mkdir /tmp/bax; cd /tmp/bax
$ touch a\  b c\  c
$ find . -type f -print | xargs -L1 wc -l
0 ./c
0 ./c
0 total
0 ./b
wc: ./a: No such file or directory

So if you don't care about the -exec option, you better use -print0 and -0:

$ find . -type f -print0 | xargs -0L1 wc -l
0 ./c
0 ./c
0 ./b
0 ./a

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

how to implement a pop up dialog box in iOS

Updated for iOS 8.0

Since iOS 8.0, you will need to use UIAlertController as the following:

-(void)alertMessage:(NSString*)message
{
    UIAlertController* alert = [UIAlertController
          alertControllerWithTitle:@"Alert"
          message:message
          preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction 
          actionWithTitle:@"OK" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.

David

illegal character in path

try

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

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

I have tried all methods, which are mentioned above.But no one method works for me.finally i got solution for above issue and it is working for me.

I tried this method:

In Html:

<li><a (click)= "aboutPageLoad()"  routerLinkActive="active">About</a></li>

In TS file:

aboutPageLoad() {
    this.router.navigate(['/about']);
}

Check if PHP-page is accessed from an iOS device

In response to Haim Evgi's code, I added !== false to the end for it to work for me

$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod") !== false;
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone") !== false;
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad") !== false;
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android") !== false;

java.net.SocketException: Connection reset

I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.

Spring MVC - How to get all request params in a map in Spring controller?

I might be late to the party, but as per my understanding , you're looking for something like this :

for(String params : Collections.list(httpServletRequest.getParameterNames())) {
    // Whatever you want to do with your map
    // Key : params
    // Value : httpServletRequest.getParameter(params)                
}

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

Ruby on Rails: How do I add placeholder text to a f.text_field?

Here is a much cleaner syntax if using rails 4+

<%= f.text_field :attr, placeholder: "placeholder text" %>

So rails 4+ can now use this syntax instead of the hash syntax

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

Private pages for a private Github repo

According to GitHub Pages documentation:

All project repositories are ready to use the generator for publishing. However, please note that private repositories will publish pages that are public.

So no, at this time there is no way to create private GitHub pages from a private GitHub repository.

EDIT:

A simple workaround

A workaround for some situations that might be helpful is to simply rename the repo to something other than the GitHub pages format while you want it to be private (for example in a development phase) and when ready to make it public then correct the name. Obviously this still doesn't help if you are looking for a way to publish pages that have authentication, but if you just want to hide a GH pages project while it's in progress, this could help.

An actual Auth Wrapper for Jekyll (GitHub pages)

Alternatively, there is a project called Jekyll Auth that GitHubber @benbalter made for such use. Jekyll Auth provides a basic authentication wrapper for jekyll projects, including GitHub pages. See the repo's README for use.

Set 4 Space Indent in Emacs in Text Mode

Have you tried

(setq  tab-width  4)

When to use Hadoop, HBase, Hive and Pig?

Cleansing Data in Pig is very easy,a suitable approach would be cleansing data through pig and then processing data through hive and later uploading it to hdfs.

Angular 5 Scroll to top on every Route click

I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

Answer from zurfyx original post

Replace duplicate spaces with a single space in T-SQL

It can be done recursively via the function:

CREATE FUNCTION dbo.RemSpaceFromStr(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
  RETURN (CASE WHEN CHARINDEX('  ', @str) > 0 THEN
    dbo.RemSpaceFromStr(REPLACE(@str, '  ', ' ')) ELSE @str END);
END

then, for example:

SELECT dbo.RemSpaceFromStr('some   string    with         many     spaces') AS NewStr

returns:

NewStr
some string with many spaces

Or the solution based on method described by @agdk26 or @Neil Knight (but safer)
both examples return output above:

SELECT REPLACE(REPLACE(REPLACE('some   string    with         many     spaces'
  , '  ', ' ' + CHAR(7)), CHAR(7) + ' ', ''), ' ' + CHAR(7), ' ') AS NewStr 
--but it remove CHAR(7) (Bell) from string if exists...

or

SELECT REPLACE(REPLACE(REPLACE('some   string    with         many     spaces'
  , '  ', ' ' + CHAR(7) + CHAR(7)), CHAR(7) + CHAR(7) + ' ', ''), ' ' + CHAR(7) + CHAR(7), ' ') AS NewStr
--but it remove CHAR(7) + CHAR(7) from string

How it works: enter image description here

Caution:
Char/string used to replace spaces shouldn't exist on begin or end of string and stand alone.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

How to get all the AD groups for a particular user?

Use tokenGroups:

DirectorySearcher ds = new DirectorySearcher();
ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
SearchResult sr = ds.FindOne();

DirectoryEntry user = sr.GetDirectoryEntry();
user.RefreshCache(new string[] { "tokenGroups" });

for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) {
    SecurityIdentifier sid = new SecurityIdentifier((byte[]) user.Properties["tokenGroups"][i], 0);
    NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount));
    //do something with the SID or name (nt.Value)
}

Note: this only gets security groups

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Dynamically create Bootstrap alerts box through JavaScript

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

There are also options that can be set on initialisation.
For your requirement you'd do:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The render method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

This is a work in progress library, but it still is in a very good working order.

MySQL error code: 1175 during UPDATE in MySQL Workbench

All that's needed is: Start a new query and run:

SET SQL_SAFE_UPDATES = 0;

Then: Run the query that you were trying to run that wasn't previously working.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

Hide/Show components in react native

enter image description here

Hide And Show parent view of Activity Indicator

constructor(props) {
  super(props)

  this.state = {
    isHidden: false
  }  
} 

Hide and Show as Follow

{
   this.state.isHidden ?  <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}

Full reference

render() {
    return (
       <View style={style.mainViewStyle}>
          <View style={style.signinStyle}>
           <TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
           <TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
           <TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
           <TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
           <TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
           <Button  style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
          </View>
          {
            this.state.isHidden ?  <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
          }
      </View>
   );
}

On Button presss set state as follow

onSignupPress() {
  this.setState({isHidden: true})
}

When you need to hide

this.setState({isHidden: false})

Formatting Decimal places in R

The function formatC() can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.

How to crop a CvMat in OpenCV?

To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :

cv::Mat source = getYourSource();

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);

cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);

CSS content generation before or after 'input' elements

Something like this works:

_x000D_
_x000D_
input + label::after {_x000D_
  content: 'click my input';_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
  content: 'not valid yet';_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
  content: 'looks good';_x000D_
  color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
_x000D_
_x000D_

Then add some floats or positioning to order stuff.

How do I define a method in Razor?

It's very simple to define a function inside razor.

@functions {

    public static HtmlString OrderedList(IEnumerable<string> items)
    { }
}

So you can call a the function anywhere. Like

@Functions.OrderedList(new[] { "Blue", "Red", "Green" })

However, this same work can be done through helper too. As an example

@helper OrderedList(IEnumerable<string> items){
    <ol>
        @foreach(var item in items){
            <li>@item</li>
        }
    </ol>
}

So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.

How to print float to n decimal places including trailing 0s?

I guess this is essentially putting it in a string, but this avoids the rounding error:

import decimal

def display(x):
    digits = 15
    temp = str(decimal.Decimal(str(x) + '0' * digits))
    return temp[:temp.find('.') + digits + 1]

cannot make a static reference to the non-static field

You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.

How to position the div popup dialog to the center of browser screen?

Note: This does not directly answer your question. This is deliberate.

A List Apart has an excellent CSS Positioning 101 article that is worth reading ... more than once. It has numerous examples that include, amongst others, your specific problem. I highly recommend it.

Active Menu Highlight CSS

Add a class to the body of each page:

<body class="home">

Or if you're on the contact page:

<body class="contact">

Then take this into consideration when you're creating your styles:

#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}

#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }

Lastly, apply class names to your list items:

<ul>
  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>
</ul>

This point, whenever you're on the body.home page, your li.home a link will have default styling indicating it is the current page.

Test if a property is available on a dynamic variable

Well, I faced a similar problem but on unit tests.

Using SharpTestsEx you can check if a property existis. I use this testing my controllers, because since the JSON object is dynamic, someone can change the name and forget to change it in the javascript or something, so testing for all properties when writing the controller should increase my safety.

Example:

dynamic testedObject = new ExpandoObject();
testedObject.MyName = "I am a testing object";

Now, using SharTestsEx:

Executing.This(delegate {var unused = testedObject.MyName; }).Should().NotThrow();
Executing.This(delegate {var unused = testedObject.NotExistingProperty; }).Should().Throw();

Using this, i test all existing properties using "Should().NotThrow()".

It's probably out of topic, but can be usefull for someone.

Is there a splice method for strings?

Simply use substr for string

ex.

var str = "Hello world!";
var res = str.substr(1, str.length);

Result = ello world!

How do I get the dialer to open with phone number displayed?

Pretty late on the answer, but if you have a TextView that you're showing the phone number in, then you don't need to deal with intents at all, you can just use the XML attribute android:autoLink="phone" and the OS will automatically initiate an ACTION_DIAL Intent.

How to clear the text of all textBoxes in the form?

Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).

 foreach (TextBox textBox in Controls.OfType<TextBox>())
    textBox.Text = "";

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

Exception in thread "main" java.util.NoSuchElementException

The nextInt() method leaves the \n (end line) symbol and is picked up immediately by nextLine(), skipping over the next input. What you want to do is use nextLine() for everything, and parse it later:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine() and then parse ints or separate words afterwards.


Also, make sure you use only one Scanner if your are only using one terminal for input. That could be another reason for the exception.


Last note: compare a String with the .equals() function, not the == operator.

if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

How can I rename a single column in a table at select?

select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2 
ON t1.Key = t2.Key 

like this ?

Add custom headers to WebView resource requests - android

You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.

There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.

Inserting a PDF file in LaTeX

Use the pdfpages package.

\usepackage{pdfpages}

To include all the pages in the PDF file:

\includepdf[pages=-]{myfile.pdf}

To include just the first page of a PDF:

\includepdf[pages={1}]{myfile.pdf}

Run texdoc pdfpages in a shell to see the complete manual for pdfpages.

What does LayoutInflater in Android do?

Inflating means reading the XML file that describes a layout (or GUI element) and to create the actual objects that correspond to it, and thus make the object visible within an Android app.

final Dialog mDateTimeDialog = new Dialog(MainActivity.this);

// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);

// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);

This file could saved as date_time_dialog.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DateTimeDialog" android:layout_width="100px"
    android:layout_height="wrap_content">
    <com.dt.datetimepicker.DateTimePicker
            android:id="@+id/DateTimePicker" android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    <LinearLayout android:id="@+id/ControlButtons"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_below="@+id/DateTimePicker"
            android:padding="5dip">
            <Button android:id="@+id/SetDateTime" android:layout_width="0dip"
                    android:text="@android:string/ok" android:layout_weight="1"
                    android:layout_height="wrap_content"
                   />
            <Button android:id="@+id/ResetDateTime" android:layout_width="0dip"
                    android:text="Reset" android:layout_weight="1"
                    android:layout_height="wrap_content"
                    />
            <Button android:id="@+id/CancelDialog" android:layout_width="0dip"
                    android:text="@android:string/cancel" android:layout_weight="1"
                    android:layout_height="wrap_content"
                     />
    </LinearLayout>

This file could saved as date_time_picker.xml:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content" `enter code here`
    android:padding="5dip" android:id="@+id/DateTimePicker">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal">

    <LinearLayout
    android:id="@+id/month_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/month_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"  
        android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/month_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:focusable="false"
        android:gravity="center"
        android:singleLine="true"
        android:textColor="#000000">
    </EditText>
    <Button
        android:id="@+id/month_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/date_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0.5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/date_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/date_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:gravity="center"
        android:focusable="false"
        android:inputType="number"
        android:textColor="#000000"
        android:singleLine="true"/>
    <Button
        android:id="@+id/date_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"      
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/year_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0.5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/year_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
            android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/year_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:gravity="center"
        android:focusable="false"
        android:inputType="number"
        android:textColor="#000000"
        android:singleLine="true"/>
    <Button
        android:id="@+id/year_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
        android:id="@+id/hour_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:id="@+id/hour_plus"
            android:layout_width="45dp"
            android:layout_height="45dp"          
            android:background="@drawable/image_button_up_final"/>
        <EditText
            android:id="@+id/hour_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:focusable="false"
            android:inputType="number"
            android:textColor="#000000"
            android:singleLine="true">
        </EditText>
        <Button
            android:id="@+id/hour_minus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_down_final"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/min_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0.35dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:id="@+id/min_plus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_up_final"/>
        <EditText
            android:id="@+id/min_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:focusable="false"
            android:inputType="number"
            android:textColor="#000000"
            android:singleLine="true"/>
        <Button
            android:id="@+id/min_minus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_down_final"/>
    </LinearLayout>

    <LinearLayout 
        android:id="@+id/meridiem_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0.35dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <ToggleButton 
            android:id="@+id/toggle_display"
            style="@style/SpecialToggleButton"
            android:layout_width="40dp"
            android:layout_height="32dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="45dp"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="5dp"
            android:padding="5dp"
            android:gravity="center"
            android:textOn="@string/meridiem_AM"
            android:textOff="@string/meridiem_PM"
            android:checked="true"/>

           <!--  android:checked="true" --> 

    </LinearLayout>
</LinearLayout>
</RelativeLayout>

The MainActivity class saved as MainActivity.java:

public class MainActivity extends Activity {
    EditText editText;
    Button button_click;
    public static Activity me = null;
    String meridiem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText)findViewById(R.id.edittext1);
        button_click = (Button)findViewById(R.id.button1);
        button_click.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view){
                final Dialog mDateTimeDialog = new Dialog(MainActivity.this);
                final RelativeLayout mDateTimeDialogView = (RelativeLayout)   getLayoutInflater().inflate(R.layout.date_time_dialog, null);
                final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
                // mDateTimePicker.setDateChangedListener();
                ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        mDateTimePicker.clearFocus();
                        int hour = mDateTimePicker.getHour();
                        String result_string = mDateTimePicker.getMonth() +" "+   String.valueOf(mDateTimePicker.getDay()) + ", " + String.valueOf(mDateTimePicker.getYear())
                        + "  " +(mDateTimePicker.getHour()<=9? String.valueOf("0"+mDateTimePicker.getHour()) : String.valueOf(mDateTimePicker.getHour())) + ":" + (mDateTimePicker.getMinute()<=9?String.valueOf("0"+mDateTimePicker.getMinute()):String.valueOf(mDateTimePicker.getMinute()))+" "+mDateTimePicker.getMeridiem();
                        editText.setText(result_string);
                        mDateTimeDialog.dismiss();
                    }
                });
                // Cancel the dialog when the "Cancel" button is clicked
                ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mDateTimeDialog.cancel();
                    }
                });
                // Reset Date and Time pickers when the "Reset" button is clicked
                ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mDateTimePicker.reset();
                    }
                });

                // Setup TimePicker
                // No title on the dialog window
                mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                // Set the dialog content view
                mDateTimeDialog.setContentView(mDateTimeDialogView);
                // Display the dialog
                mDateTimeDialog.show();
            }
        });
    }
}

java collections - keyset() vs entrySet() in map

Traversal over the large map entrySet() is much better than the keySet(). Check this tutorial how they optimise the traversal over the large object with the help of entrySet() and how it helps for performance tuning.

Creating .pem file for APNS?

Steps:

  1. Create a CSR Using Key Chain Access
  2. Create a P12 Using Key Chain Access using private key
  3. APNS App ID and certificate

This gives you three files:

  • The CSR
  • The private key as a p12 file (PushChatKey.p12)
  • The SSL certificate, aps_development.cer

Go to the folder where you downloaded the files, in my case the Desktop:

$ cd ~/Desktop/

Convert the .cer file into a .pem file:

$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem

Convert the private key’s .p12 file into a .pem file:

$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12

Enter Import Password:

MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase:

You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure. Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Finally, combine the certificate and key into a single .pem file:

$ cat PushChatCert.pem PushChatKey.pem > ck.pem

setState() inside of componentDidUpdate()

The componentDidUpdate signature is void::componentDidUpdate(previousProps, previousState). With this you will be able to test which props/state are dirty and call setState accordingly.

Example:

componentDidUpdate(previousProps, previousState) {
    if (previousProps.data !== this.props.data) {
        this.setState({/*....*/})
    }
}

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

How to change default text color using custom theme?

You can't use @android:style/TextAppearance as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.

To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).

res/values/themes.xml:

<resources>    
    <style name="MyAppTheme" parent="android:Theme.Holo.Light">
        <!-- Change default text colour from dark grey to black -->
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>

Manifest:

<application
    ...
    android:theme="@style/MyAppTheme">

Update

A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)

As I learned by asking this question, a better way is to define the colour using a drawable:

<item name="android:textColor">@drawable/default_text_color</item>

...with res/drawable/default_text_color.xml specifying separate state_enabled="false" colour:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

Can't Load URL: The domain of this URL isn't included in the app's domains

Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!

And pay attention for one detail here:

In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000

Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...

enter image description here

ImportError: DLL load failed: %1 is not a valid Win32 application

This error can also appear when python versions are mixed:

For example if any of the DLL to be loaded has been compiled using python 2.7.16 and you try to import with python 2.7.15 this error ImportError: DLL load failed: %1 is not a valid Win32 application. is thrown.

This is at least what I've found to be the problem in my case.

Pass a PHP array to a JavaScript function

Use JSON.

In the following example $php_variable can be any PHP variable.

<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>

In your code, you could use like the following:

drawChart(600/50, <?php echo json_encode($day); ?>, ...)

In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:

var s = "<JSON-String>";
var obj = JSON.parse(s);

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

Unable to show a Git tree in terminal

How can you get the tree-like view of commits in terminal?

git log --graph --oneline --all

is a good start.

You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc:

export LESS="-R"

such that you do not need use Tig's ASCII filter by

git log --graph --pretty=oneline --abbrev-commit | tig   // Masi needed this 

The article text-based graph from Git-ready contains other options:

git log --graph --pretty=oneline --abbrev-commit

git log graph

Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.


Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph option back in 2007.

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

Check for special characters (/*-+_@&$#%) in a string?

The easiest way it to use a regular expression:

Regular Expression for alphanumeric and underscores

Using regular expressions in .net:

http://www.regular-expressions.info/dotnet.html

MSDN Regular Expression

Regex.IsMatch

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

if(regexItem.IsMatch(YOUR_STRING)){..}

What does it mean to "program to an interface"?

Program to an interface allows to change implementation of contract defined by interface seamlessly. It allows loose coupling between contract and specific implementations.

IInterface classRef = new ObjectWhatever()

You could use any class that implements IInterface? When would you need to do that?

Have a look at this SE question for good example.

Why should the interface for a Java class be preferred?

does using an Interface hit performance?

if so how much?

Yes. It will have slight performance overhead in sub-seconds. But if your application has requirement to change the implementation of interface dynamically, don't worry about performance impact.

how can you avoid it without having to maintain two bits of code?

Don't try to avoid multiple implementations of interface if your application need them. In absence of tight coupling of interface with one specific implementation, you may have to deploy the patch to change one implementation to other implementation.

One good use case: Implementation of Strategy pattern:

Real World Example of the Strategy Pattern

Invoking a jQuery function after .each() has completed

If you're willing to make it a couple of steps, this might work. It's dependent on the animations finishing in order, though. I don't think that should be a problem.

var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;

elems.each( function(i) {
    $(this).fadeOut(200, function() { 
        $(this).remove(); 
        if (i == lastID) {
           doMyThing();
        }
    });
});

Java: Check if command line arguments are null

You should check for (args == null || args.length == 0). Although the null check isn't really needed, it is a good practice.

Difference Between Select and SelectMany

Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.

object==null or null==object?

This also closely relates to:

if ("foo".equals(bar)) {

which is convenient if you don't want to deal with NPEs:

if (bar!=null && bar.equals("foo")) {

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

How to run a SQL query on an Excel table?

You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.

However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.

Maven fails to find local artifact

I had the same error from a different cause: I'd created a starter POM containing our "good practice" dependencies, and built & installed it locally to test it. I could "see" it in the repo, but a project that used it got the above error. What I'd done was set the starter POM to pom, so there was no JAR. Maven was quite correct that it wasn't in Nexus -- but I wasn't expecting it to be, so the error was, ummm, unhelpful. Changing the starter POM to normal packaging & reinstalling fixed the issue.

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Deleting an object in java?

If you want help an object go away, set its reference to null.

String x = "sadfasdfasd";
// do stuff
x = null;

Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.

How to assign a select result to a variable?

Try This

SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key

UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey 
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key

You would declare this variable outside of your loop as just a standard TSQL variable.

I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.

Rotating a two-dimensional array in Python

I've had this problem myself and I've found the great wikipedia page on the subject (in "Common rotations" paragraph:
https://en.wikipedia.org/wiki/Rotation_matrix#Ambiguities

Then I wrote the following code, super verbose in order to have a clear understanding of what is going on.

I hope that you'll find it useful to dig more in the very beautiful and clever one-liner you've posted.

To quickly test it you can copy / paste it here:
http://www.codeskulptor.org/

triangle = [[0,0],[5,0],[5,2]]
coordinates_a = triangle[0]
coordinates_b = triangle[1]
coordinates_c = triangle[2]

def rotate90ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]
# Here we apply the matrix coming from Wikipedia
# for 90 ccw it looks like:
# 0,-1
# 1,0
# What does this mean?
#
# Basically this is how the calculation of the new_x and new_y is happening:
# new_x = (0)(old_x)+(-1)(old_y)
# new_y = (1)(old_x)+(0)(old_y)
#
# If you check the lonely numbers between parenthesis the Wikipedia matrix's numbers
# finally start making sense.
# All the rest is standard formula, the same behaviour will apply to other rotations, just
# remember to use the other rotation matrix values available on Wiki for 180ccw and 170ccw
    new_x = -old_y
    new_y = old_x
    print "End coordinates:"
    print [new_x, new_y]

def rotate180ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1] 
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

def rotate270ccw(coordinates):
    print "Start coordinates:"
    print coordinates
    old_x = coordinates[0]
    old_y = coordinates[1]  
    new_x = -old_x
    new_y = -old_y
    print "End coordinates:"
    print [new_x, new_y]

print "Let's rotate point A 90 degrees ccw:"
rotate90ccw(coordinates_a)
print "Let's rotate point B 90 degrees ccw:"
rotate90ccw(coordinates_b)
print "Let's rotate point C 90 degrees ccw:"
rotate90ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 180 degrees ccw:"
rotate180ccw(coordinates_a)
print "Let's rotate point B 180 degrees ccw:"
rotate180ccw(coordinates_b)
print "Let's rotate point C 180 degrees ccw:"
rotate180ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 270 degrees ccw:"
rotate270ccw(coordinates_a)
print "Let's rotate point B 270 degrees ccw:"
rotate270ccw(coordinates_b)
print "Let's rotate point C 270 degrees ccw:"
rotate270ccw(coordinates_c)
print "=== === === === === === === === === "

Magento - How to add/remove links on my account navigation?

If you want to selectively remove links without having to copy/edit entire xml files, a nice solution can be found in this post in the magento forums

In this solution, you override the Mage_Customer_Block_Account_Navigation block with a local version, that adds a removeLinkByName method, which you then use in your layout.xml files, like so:

<?xml version="1.0"?>
    <layout version="0.1.0">

    <customer_account>
        <reference name="customer_account_navigation" >
                <!-- remove the link using your custom method -->
                <action method="removeLinkByName">
                   <name>recurring_profiles</name>
                </action>
                <action method="removeLinkByName">
                   <name>billing_agreements</name>
                </action>
        </reference>
    </customer_account>
</layout>

Self Join to get employee manager name

As Jesse said, use self join:

SELECT 
  e.emp_id
  , e.emp_name
  , e.emp_mgr_id
  , m.emp_name AS mgr_name 
FROM [dbo].[tblEmployeeDetails] e 
LEFT JOIN [dbo].[tblEmployeeDetails] m ON e.emp_mgr_id = m.emp_id

Disposing WPF User Controls

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
    {
        // Dispose of any Disposable items here
    }

Pandas get the most frequent values of a column

You could try argmax like this:

dataframe['name'].value_counts().argmax() Out[13]: 'alex'

The value_counts will return a count object of pandas.core.series.Series and argmax could be used to achieve the key of max values.

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.

This happens even if you set

crossOrigin: false;

or even if you ommit it.

The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.

PHP - Insert date into mysql

Unless you want to insert different dates than "today", you can use CURDATE():

$sql = 'INSERT INTO data_tables (title, date_of_event) VALUES ("%s", CURDATE())';
$sql = sprintf ($sql, $_POST['post_title']);

PS! Please do not forget to sanitize your MySQL input, especially via mysql_real_escape_string ()

In PHP with PDO, how to check the final SQL parametrized query?

You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .

C++ correct way to return pointer to array from function

In a real app, the way you returned the array is called using an out parameter. Of course you don't actually have to return a pointer to the array, because the caller already has it, you just need to fill in the array. It's also common to pass another argument specifying the size of the array so as to not overflow it.

Using an out parameter has the disadvantage that the caller may not know how large the array needs to be to store the result. In that case, you can return a std::vector or similar array class instance.

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

How much data can a List can hold at the maximum?

It would depend on the implementation, but the limit is not defined by the List interface.

The interface however defines the size() method, which returns an int.

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit

ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE

HtmlEncode from Class Library

In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:

Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);