Programs & Examples On #Search form

Align nav-items to right side in bootstrap-4

In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the <ul class="navbar-nav"> and then add the ml-auto class to your navbar item.

fail to change placeholder color with Bootstrap 3

You should check out this answer : Change an HTML5 input's placeholder color with CSS

Work on most browser, the solution in this thread is not working on FF 30+ for example

How to display Wordpress search results?

you need to include the Wordpress loop in your search.php this is example

search.php template file:

<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

JavaScript: how to change form action attribute value based on selection?

It's better to use

$('#search-form').setAttribute('action', '/controllerName/actionName');

rather than

$('#search-form').attr('action', '/controllerName/actionName');

So, based on trante's answer we have:

$('#search-form').submit(function() {
    var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
    $("#search-form").setAttribute("action", "/search/" + formAction);
}); 

Using setAttribute can save you a lot of time potentially.

Removing white space around a saved image in matplotlib

I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = 'tight',
    pad_inches = 0)

I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.

Cannot make file java.io.IOException: No such file or directory

Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.

Permissions app

Step-by-step debugging with IPython

Looks like the approach in @gaborous's answer is deprecated.

The new approach seems to be:

from IPython.core import debugger
debug = debugger.Pdb().set_trace

def buggy_method():
    debug()

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

Rails: update_attribute vs update_attributes

update_attribute simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes method.

Example:

user = User.last

#update_attribute
user.update_attribute(:status, "active")

It pass the validation

#update_attributes
user.update_attributes(first_name: 'update name', status: "active")

it doesn't update if validation fails.

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

Set SSH connection timeout

The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".

The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.

Are HTTP cookies port specific?

In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.

I've posted this answer so that readers will have at least one concrete option for testing each scenario.

Copying PostgreSQL database to another server

I struggled quite a lot and eventually the method that allowed me to make it work with Rails 4 was:

on your old server

sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql

I had to use the postgres linux user to create the dump. also i had to use -c to force the creation of the database on the new server. --inserts tells it to use the INSERT() syntax which otherwise would not work for me :(

then, on the new server, simpy:

sudo su - postgres
psql new_database_name < dump.sql

to transfer the dump.sql file between server I simply used the "cat" to print the content and than "nano" to recreate it copypasting the content.

Also, the ROLE i was using on the two database was different so i had to find-replace all the owner name in the dump.

When is del useful in Python?

To add a few points to above answers: del x

Definition of x indicates r -> o (a reference r pointing to an object o) but del x changes r rather than o. It is an operation on the reference (pointer) to object rather than the object associated with x. Distinguishing between r and o is key here.

  • It removes it from locals().
  • Removes it from globals() if x belongs there.
  • Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame).
  • Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems.
  • It is more about declaration of the name rather than definition of content.
  • It affects where x belongs to, not where x points to. The only physical change in memory is this. For example if x is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()), which overlaps with globals().

Get the first element of an array

As Mike pointed out (the easiest possible way):

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); // Echoes "apple"

If you want to get the key: (execute it after reset)

echo key($arr); // Echoes "4"

From PHP's documentation:

mixed reset ( array &$array );

Description:

reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.

Alternative to iFrames with HTML5

object is an easy alternative in HTML5:

_x000D_
_x000D_
<object data="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width="400"
height="300"
type="text/html">
    Alternative Content
</object>
_x000D_
_x000D_
_x000D_

You can also try embed:

_x000D_
_x000D_
<embed src="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width=200
height=200
onerror="alert('URL invalid !!');" />
_x000D_
_x000D_
_x000D_

Re-

As currently, StackOverflow has turned off support for showing external URL contents, run code snippet is not showing anything. But for your site, it will work perfactly.

How to capitalize the first character of each word in a string

With this simple code:

String example="hello";

example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());

System.out.println(example);

Result: Hello

Where in memory are my variables stored in C?

A popular desktop architecture divides a process's virtual memory in several segments:

  • Text segment: contains the executable code. The instruction pointer takes values in this range.

  • Data segment: contains global variables (i.e. objects with static linkage). Subdivided in read-only data (such as string constants) and uninitialized data ("BSS").

  • Stack segment: contains the dynamic memory for the program, i.e. the free store ("heap") and the local stack frames for all the threads. Traditionally the C stack and C heap used to grow into the stack segment from opposite ends, but I believe that practice has been abandoned because it is too unsafe.

A C program typically puts objects with static storage duration into the data segment, dynamically allocated objects on the free store, and automatic objects on the call stack of the thread in which it lives.

On other platforms, such as old x86 real mode or on embedded devices, things can obviously be radically different.

Calling a Function defined inside another function in Javascript

You are not calling the function inner, just defining it.

function outer() { 
    function inner() {
        alert("hi");
    }

    inner(); //Call the inner function

}

Avoid trailing zeroes in printf()

A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):

// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
    return (fabs(i - j) < 0.000001);
}

void PrintMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%.2f", d);
    else
        printf("%.3f", d);
}

Add or remove "elses" if you want a max of 2 decimals; 4 decimals; etc.

For example if you wanted 2 decimals:

void PrintMaxTwoDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else
        printf("%.2f", d);
}

If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:

void PrintAlignedMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%7.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%9.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%10.2f", d);
    else
        printf("%11.3f", d);
}

You could also convert that to a function where you pass the desired width of the field:

void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%*.0f", w-4, d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%*.1f", w-2, d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%*.2f", w-1, d);
    else
        printf("%*.3f", w, d);
}

Jackson enum Serializing and DeSerializer

Actual Answer:

The default deserializer for enums uses .name() to deserialize, so it's not using the @JsonValue. So as @OldCurmudgeon pointed out, you'd need to pass in {"event": "FORGOT_PASSWORD"} to match the .name() value.

An other option (assuming you want the write and read json values to be the same)...

More Info:

There is (yet) another way to manage the serialization and deserialization process with Jackson. You can specify these annotations to use your own custom serializer and deserializer:

@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserializer.class)
public final class MyClass {
    ...
}

Then you have to write MySerializer and MyDeserializer which look like this:

MySerializer

public final class MySerializer extends JsonSerializer<MyClass>
{
    @Override
    public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
    {
        // here you'd write data to the stream with gen.write...() methods
    }

}

MyDeserializer

public final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>
{
    @Override
    public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
    {
        // then you'd do something like parser.getInt() or whatever to pull data off the parser
        return null;
    }

}

Last little bit, particularly for doing this to an enum JsonEnum that serializes with the method getYourValue(), your serializer and deserializer might look like this:

public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
    gen.writeString(enumValue.getYourValue());
}

public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
    final String jsonValue = parser.getText();
    for (final JsonEnum enumValue : JsonEnum.values())
    {
        if (enumValue.getYourValue().equals(jsonValue))
        {
            return enumValue;
        }
    }
    return null;
}

How to add rows dynamically into table layout

You are doing it right; every time you need to add a row, simply so new TableRow(), etc. It might be easier for you to inflate the new row from XML though.

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

I wrapped @smileyborg's iOS7 solution in a category

I decided to wrap this clever solution by @smileyborg into a UICollectionViewCell+AutoLayoutDynamicHeightCalculation category.

The category also rectifies the issues outlined in @wildmonkey's answer (loading a cell from a nib and systemLayoutSizeFittingSize: returning CGRectZero)

It doesn't take into account any caching but suits my needs right now. Feel free to copy, paste and hack at it.

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.h

#import <UIKit/UIKit.h>

typedef void (^UICollectionViewCellAutoLayoutRenderBlock)(void);

/**
 *  A category on UICollectionViewCell to aid calculating dynamic heights based on AutoLayout contraints.
 *
 *  Many thanks to @smileyborg and @wildmonkey
 *
 *  @see stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights
 */
@interface UICollectionViewCell (AutoLayoutDynamicHeightCalculation)

/**
 *  Grab an instance of the receiving type to use in order to calculate AutoLayout contraint driven dynamic height. The method pulls the cell from a nib file and moves any Interface Builder defined contrainsts to the content view.
 *
 *  @param name Name of the nib file.
 *
 *  @return collection view cell for using to calculate content based height
 */
+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name;

/**
 *  Returns the height of the receiver after rendering with your model data and applying an AutoLayout pass
 *
 *  @param block Render the model data to your UI elements in this block
 *
 *  @return Calculated constraint derived height
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width;

/**
 *  Directly calls `heightAfterAutoLayoutPassAndRenderingWithBlock:collectionViewWidth` assuming a collection view width spanning the [UIScreen mainScreen] bounds
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block;

@end

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.m

#import "UICollectionViewCell+AutoLayout.h"

@implementation UICollectionViewCell (AutoLayout)

#pragma mark Dummy Cell Generator

+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name
{
    UICollectionViewCell *heightCalculationCell = [[[NSBundle mainBundle] loadNibNamed:name owner:self options:nil] lastObject];
    [heightCalculationCell moveInterfaceBuilderLayoutConstraintsToContentView];
    return heightCalculationCell;
}

#pragma mark Moving Constraints

- (void)moveInterfaceBuilderLayoutConstraintsToContentView
{
    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        [self removeConstraint:constraint];
        id firstItem = constraint.firstItem == self ? self.contentView : constraint.firstItem;
        id secondItem = constraint.secondItem == self ? self.contentView : constraint.secondItem;
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:firstItem
                                                                     attribute:constraint.firstAttribute
                                                                     relatedBy:constraint.relation
                                                                        toItem:secondItem
                                                                     attribute:constraint.secondAttribute
                                                                    multiplier:constraint.multiplier
                                                                      constant:constraint.constant]];
    }];
}

#pragma mark Height

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block
{
    return [self heightAfterAutoLayoutPassAndRenderingWithBlock:block
                                            collectionViewWidth:CGRectGetWidth([[UIScreen mainScreen] bounds])];
}

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width
{
    NSParameterAssert(block);

    block();

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];

    self.bounds = CGRectMake(0.0f, 0.0f, width, CGRectGetHeight(self.bounds));

    [self setNeedsLayout];
    [self layoutIfNeeded];

    CGSize calculatedSize = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    return calculatedSize.height;

}

@end

Usage example:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MYSweetCell *cell = [MYSweetCell heightCalculationCellFromNibWithName:NSStringFromClass([MYSweetCell class])];
    CGFloat height = [cell heightAfterAutoLayoutPassAndRenderingWithBlock:^{
        [(id<MYSweetCellRenderProtocol>)cell renderWithModel:someModel];
    }];
    return CGSizeMake(CGRectGetWidth(self.collectionView.bounds), height);
}

Thankfully we won't have to do this jazz in iOS8, but there it is for now!

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

there is a .bat script to start it (python 2.7).

c:\Python27\Lib\idlelib\idle.bat

Finding and removing non ascii characters from an Oracle Varchar2

Answer given by Francisco Hayoz is the best. Don't use pl/sql functions if sql can do it for you.

Here is the simple test in Oracle 11.2.03

select s
     , regexp_replace(s,'[^'||chr(1)||'-'||chr(127)||']','') "rep ^1-127"
     , dump(regexp_replace(s,'['||chr(127)||'-'||chr(225)||']','')) "rep 127-255"
from (
select listagg(c, '') within group (order by c) s
  from (select 127+level l,chr(127+level) c from dual connect by level < 129))

And "rep 127-255" is

Typ=1 Len=30: 226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255

i.e for some reason this version of Oracle does not replace char(226) and above. Using '['||chr(127)||'-'||chr(225)||']' gives the desired result. If you need to replace other characters just add them to the regex above or use nested replace|regexp_replace if the replacement is different then '' (null string).

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

Server configuration is missing in Eclipse

In my case, the server list was empty for Apache in "Run Configurations" when I opened

Run > Run Configurations enter image description here

I fixed this by creating a server in the Servers Panel as in other answers:

  1. Window -> Show view -> Servers
  2. Right click -> New -> Server : to create a new one

enter image description here

enter image description here

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

What is the best project structure for a Python application?

Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.

  • /scripts or /bin for that kind of command-line interface stuff
  • /tests for your tests
  • /lib for your C-language libraries
  • /doc for most documentation
  • /apidoc for the Epydoc-generated API docs.

And the top-level directory can contain README's, Config's and whatnot.

The hard choice is whether or not to use a /src tree. Python doesn't have a distinction between /src, /lib, and /bin like Java or C has.

Since a top-level /src directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.

  • /foo
  • /bar
  • /baz

I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux, the directory that contains all this stuff is named /quux.

Another project's PYTHONPATH, then, can include /path/to/quux/foo to reuse the QUUX.foo module.

In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux directory, and omit adding it to SVN.

Detect element content changes with jQuery

These are mutation events.

I have not used mutation event APIs in jQuery, but a cursory search led me to this project on GitHub. I am unaware of the project's maturity.

What permission do I need to access Internet from an Android application?

Just put below code in AndroidManifest :

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

Can I concatenate multiple MySQL rows into one field?

You can use GROUP_CONCAT:

SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Ludwig stated in his comment, you can add the DISTINCT operator to avoid duplicates:

SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Jan stated in their comment, you can also sort the values before imploding it using ORDER BY:

SELECT person_id, 
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Dag stated in his comment, there is a 1024 byte limit on the result. To solve this, run this query before your query:

SET group_concat_max_len = 2048;

Of course, you can change 2048 according to your needs. To calculate and assign the value:

SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

FIFO class in Java

You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How do I import a specific version of a package using go get?

go get is the Go package manager. It works in a completely decentralized way and how package discovery still possible without a central package hosting repository.

Besides locating and downloading packages, the other big role of a package manager is handling multiple versions of the same package. Go takes the most minimal and pragmatic approach of any package manager. There is no such thing as multiple versions of a Go package.

go get always pulls from the HEAD of the default branch in the repository. Always. This has two important implications:

  1. As a package author, you must adhere to the stable HEAD philosophy. Your default branch must always be the stable, released version of your package. You must do work in feature branches and only merge when ready to release.

  2. New major versions of your package must have their own repository. Put simply, each major version of your package (following semantic versioning) would have its own repository and thus its own import path.

    e.g. github.com/jpoehls/gophermail-v1 and github.com/jpoehls/gophermail-v2.

As someone building an application in Go, the above philosophy really doesn't have a downside. Every import path is a stable API. There are no version numbers to worry about. Awesome!

For more details : http://zduck.com/2014/go-and-package-versioning/

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

Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/ directory if you are using a linux OS.

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

How to change the integrated terminal in visual studio code or VSCode

I was successful via settings > Terminal > Integrated > Shell: Linux

from there I edited the path of the shell to be /bin/zsh from the default /bin/bash

  • there are also options for OSX and Windows as well

screencap of vs settings view

@charlieParker - here's what i'm seeing for available commands in the command pallette

enter image description here

Cannot GET / Nodejs Error

Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:

node_modules/
  .bin/
  express/
  mongoose/
  path/
site/
  css/
  img/
  js/
  index.html
package.json

For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.

Hope that helps!

How to turn off the Eclipse code formatter for certain sections of Java code?

You have to turn on the ability to add the formatter tags. In the menubar go to:

Windows Preferences Java Code Style Formatter

Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.

Generate UML Class Diagram from Java Project

I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Interfaces — What's the point?

Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.

I'll just give an example supported by the graphic below.

Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.

enter image description here

A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.

public interface IMachine
{
    bool Start();
    bool Stop();
}

public class Car : IMachine
{
    public bool Start()
    {
        Console.WriteLine("Car started");
        return true;
    }

    public bool Stop()
    {
        Console.WriteLine("Car stopped");
        return false;
    }
}

public class Tank : IMachine
{
    public bool Start()
    {
        Console.WriteLine("Tank started");
        return true;
    }

    public bool Stop()
    {
        Console.WriteLine("Tank stopped");
        return false;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var car = new Car();
        car.Start();
        car.Stop();

        var tank = new Tank();
        tank.Start();
        tank.Stop();

    }
}

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to split one string into multiple strings separated by at least one space in bash shell?

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"

Can't create project on Netbeans 8.2

Yes it s working: remove the path of jdk 9.0 and uninstall this from Cantroll panel instead install jdk 8version and set it's path, it is working easily with netbean 8.2.

"Untrusted App Developer" message when installing enterprise iOS Application

This issue comes when trust verification of app fails.

Screenshot 1

You can trust app from Settings shown in below images.

Screenshot 2

Screenshot 3

Screenshot 4

If this dosen't work then delete app and re-install it.

How do you find out the caller function in JavaScript?

I wanted to add my fiddle here for this:

http://jsfiddle.net/bladnman/EhUm3/

I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.

Java generics - ArrayList initialization

Think of the ? as to mean "unknown". Thus, "ArrayList<? extends Object>" is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3) would be putting something you know, into an unknown. I.e 'Forgetting'.

adb uninstall failed

This worked for me:

This is the directory where all the APKs are stored:

cd /system/app

List them:

ls

Choose one to remove.

pm install -r <app_to_remove>.apk

Example:

$ pm install -r Google-Play-services.apk
        pkg: Google-Play-services.apk
Success


I noticed that I get failure if the application I'm trying to remove is running, so kill it first.

Also, I noticed you might have to run (on a rooted device):

$ su
# mount -o remount +rw /

How do I get a reference to the app delegate in Swift?

In Swift 3.0 you can get the appdelegate reference by

let appDelegate = UIApplication.shared.delegate as! AppDelegate

Running code in main thread from another thread

Follow this method. Using this way you can simply update the UI from a background thread. runOnUiThread work on the main(UI) thread . I think this code snippet is less complex and easy, especially for beginners.

AsyncTask.execute(new Runnable() {
            @Override
            public void run() {

            //code you want to run on the background
            someCode();

           //the code you want to run on main thread
 MainActivity.this.runOnUiThread(new Runnable() {

                    public void run() {

/*the code you want to run after the background operation otherwise they will executed earlier and give you an error*/
                        executeAfterOperation();

                   }
                });
            }
        });

in the case of a service

create a handler in the oncreate

 handler = new Handler();

then use it like this

 private void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }

Keyboard shortcuts in WPF

Documenting this answer for others, as there is a much simpler way to do this that is rarely referenced, and doesn't require touching the XAML at all.

To link a keyboard shortcut, in the Window constructor simply add a new KeyBinding to the InputBindings collection. As the command, pass in your arbitrary command class that implements ICommand. For the execute method, simply implement whatever logic you need. In my example below, my WindowCommand class takes a delegate that it will execute whenever invoked. When I construct the new WindowCommand to pass in with my binding, I simply indicate in my initializer, the method that I want the WindowCommand to execute.

You can use this pattern to come up with your own quick keyboard shortcuts.

public YourWindow() //inside any WPF Window constructor
{
   ...
   //add this one statement to bind a new keyboard command shortcut
   InputBindings.Add(new KeyBinding( //add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
      new WindowCommand(this)
      {
         ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
      }, new KeyGesture(Key.P, ModifierKeys.Control)));
   ...
}

Create a simple WindowCommand class which takes an execution delegate to fire off any method set on it.

public class WindowCommand : ICommand
{
    private MainWindow _window;

    //Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
    public Action ExecuteDelegate { get; set; }

    //You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
    public WindowCommand(MainWindow window)
    {
        _window = window;
    }

    //always called before executing the command, mine just always returns true
    public bool CanExecute(object parameter)
    {
        return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
    }

    public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface

    //the important method that executes the actual command logic
    public void Execute(object parameter)
    {
        if (ExecuteDelegate != null)
        {
            ExecuteDelegate();
        }
        else
        {
            throw new InvalidOperationException();
        }
    }
}

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

One thing that really helped me was adding the ".exe" on the Debug folder to the Exclusions on my Anti-Virus.

How to get script of SQL Server data?

I had a hell of a time finding this option in SQL Management Studio 2012, but I finally found it. The option is hiding in the Advanced button in the screen below.

I always assumed this contained just assumed advanced options for File generation, since that's what it's next to, but it turns out someone at MS is just really bad at UI design in this case. HTH somebody who comes to this thread like I did.

SQL Management Studio 2012

How to read existing text files without defining path

You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:

string fullPathToFile = Path.Combine(dir, fileName);

If you don't supply the base directory dir then you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.

For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.

Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.

One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.

jQuery delete all table rows except first

Easiest way :

$("#mytable").find($("tr")).slice(1).remove()

-first reference the table
-get the list of elements and slice it and remove the selected elements of the list

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

How does python numpy.where() work?

Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.

so:

>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
       65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
       82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
       99]),)
>>> np.where(a == 90)
(array([90]),)

a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
       94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040

I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

New Answer It seems that the person was asking something more fundamental.

The question was how could YOU implement something that allows a function (such as where) to know what was requested.

First note that calling any of the comparison operators do an interesting thing.

a > 1000
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True`,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)`

This is done by overloading the "__gt__" method. For instance:

>>> class demo(object):
    def __gt__(self, item):
        print item


>>> a = demo()
>>> a > 4
4

As you can see, "a > 4" was valid code.

You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html

Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!

Converting double to string

Using Double.toString(), if the number is too small or too large, you will get a scientific notation like this: 3.4875546345347673E-6. There are several ways to have more control of output string format.

double num = 0.000074635638;
// use Double.toString()
System.out.println(Double.toString(num));
// result: 7.4635638E-5

// use String.format
System.out.println(String.format ("%f", num));
// result: 0.000075
System.out.println(String.format ("%.9f", num));
// result: 0.000074636

// use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000");
String numberAsString = decimalFormat.format(num);
System.out.println(numberAsString);
// result: 0.000075

Use String.format() will be the best convenient way.

What is the difference between Select and Project Operations

The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For higher version of phpunit such as 6.4 You must use the namespace PHPUnit\Framework\TestCase

use TestCase instead PHPUnit_Framework_TestCase

// use the following namespace
use PHPUnit\Framework\TestCase;

// extend using TestCase instead PHPUnit_Framework_TestCase
class SampleTest extends TestCase {

}

difference between variables inside and outside of __init__()

Without Self

Create some objects:

class foo(object):
    x = 'original class'

c1, c2 = foo(), foo()

I can change the c1 instance, and it will not affect the c2 instance:

c1.x = 'changed instance'
c2.x
>>> 'original class'

But if I change the foo class, all instances of that class will be changed as well:

foo.x = 'changed class'
c2.x
>>> 'changed class'

Please note how Python scoping works here:

c1.x
>>> 'changed instance'

With Self

Changing the class does not affect the instances:

class foo(object):
    def __init__(self):
        self.x = 'original self'

c1 = foo()
foo.x = 'changed class'
c1.x
>>> 'original self'

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

Create session factory in Hibernate 4

[quote from http://www.javabeat.net/session-factory-hibernate-4/]

There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

Linux: copy and create destination dir if it does not exist

cp has multiple usages:

$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
  or:  cp [OPTION]... SOURCE... DIRECTORY
  or:  cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

@AndyRoss's answer works for the

cp SOURCE DEST

style of cp, but does the wrong thing if you use the

cp SOURCE... DIRECTORY/

style of cp.

I think that "DEST" is ambiguous without a trailing slash in this usage (i.e. where the target directory doesn't yet exist), which is perhaps why cp has never added an option for this.

So here's my version of this function which enforces a trailing slash on the dest dir:

cp-p() {
  last=${@: -1}

  if [[ $# -ge 2 && "$last" == */ ]] ; then
    # cp SOURCE... DEST/
    mkdir -p "$last" && cp "$@"
  else
    echo "cp-p: (copy, creating parent dirs)"
    echo "cp-p: Usage: cp-p SOURCE... DEST/"
  fi
}

How to insert a text at the beginning of a file?

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

The best solution will add the string, but with the string, it will not add a line at the end of a file.

sed -i '1s/^/your text\n/' file

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

Can I automatically increment the file build version when using Visual Studio?

I have created an application to increment the file version automatically.

  1. Download Application
  2. add the following line to pre-build event command line

    C:\temp\IncrementFileVersion.exe $(SolutionDir)\Properties\AssemblyInfo.cs

  3. Build the project

To keep it simple the app only throws messages if there is an error, to confirm it worked fine you will need to check the file version in 'Assembly Information'

Note : You will have to reload the solution in Visual studio for 'Assembly Information' button to populate the fields, however your output file will have the updated version.

For suggestions and requests please email me at [email protected]

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

Getting a slice of keys from a map

This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

keys := make([]int, len(mymap))

i := 0
for k := range mymap {
    keys[i] = k
    i++
}

In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

What is the advantage of using REST instead of non-REST HTTP?

Caching.

There are other more in depth benefits of REST which revolve around evolve-ability via loose coupling and hypertext, but caching mechanisms are the main reason you should care about RESTful HTTP.

What is the difference between a heuristic and an algorithm?

A heuristic is usually an optimization or a strategy that usually provides a good enough answer, but not always and rarely the best answer. For example, if you were to solve the traveling salesman problem with brute force, discarding a partial solution once its cost exceeds that of the current best solution is a heuristic: sometimes it helps, other times it doesn't, and it definitely doesn't improve the theoretical (big-oh notation) run time of the algorithm

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

JSON.NET Error Self referencing loop detected for type

C# code:

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            };

            var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);

            var filePath = @"E:\json.json";

            File.WriteAllText(filePath, jsonString);

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

How to make ng-repeat filter out duplicate results

If you want to get unique data based on the nested key:

app.filter('unique', function() {
        return function(collection, primaryKey, secondaryKey) { //optional secondary key
          var output = [], 
              keys = [];

          angular.forEach(collection, function(item) {
                var key;
                secondaryKey === undefined ? key = item[primaryKey] : key = item[primaryKey][secondaryKey];

                if(keys.indexOf(key) === -1) {
                  keys.push(key);
                  output.push(item);
                }
          });

          return output;
        };
    });

Call it like this :

<div ng-repeat="notify in notifications | unique: 'firstlevel':'secondlevel'">

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

Update Eclipse with Android development tools v. 23

There are many possible answers to this question. I think it all depends on what your environment and installation procedure is. I'm running into the same issue as stated multiple times above. I cannot install ADT 23 because of a conflict dependency.

This is my environment:

I'm running Windows 7 64-bit with Eclipse 4.2.2. I installed ADT through menu Help ? Install New Software.

My solution:

Menu Help ? About Eclipse ? Uninstall ? ALL_ANDROID. Then I simply installed each of the ADT 23 tools through the "Install New Software".

Note: This is with the LATEST ADT release.

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

URL Encode a string in jQuery for an AJAX request

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);

How do I find if a string starts with another string in Ruby?

Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:

irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
=> 12.477248
irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
=> 9.593959
irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
=> 9.086909
irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
=> 6.973697

So it looks like start_with? ist the fastest of the bunch.

Updated results with Ruby 2.2.2p95 and a newer machine:

require 'benchmark'
Benchmark.bm do |x|
  x.report('regex[]')    { 10000000.times { "foobar"[/\Afoo/] }}
  x.report('regex')      { 10000000.times { "foobar" =~ /\Afoo/ }}
  x.report('[]')         { 10000000.times { "foobar"["foo"] }}
  x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
end

            user       system     total       real
regex[]     4.020000   0.000000   4.020000 (  4.024469)
regex       3.160000   0.000000   3.160000 (  3.159543)
[]          2.930000   0.000000   2.930000 (  2.931889)
start_with  2.010000   0.000000   2.010000 (  2.008162)

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

Call to undefined function mysql_query() with Login

You are mixing mysql and mysqli

Change these lines:

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

to

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

moving changed files to another branch for check-in

A soft git reset will put committed changes back into your index. Next, checkout the branch you had intended to commit on. Then git commit with a new commit message.

  1. git reset --soft <commit>

  2. git checkout <branch>

  3. git commit -m "Commit message goes here"

From git docs:

git reset [<mode>] [<commit>] This form resets the current branch head to and possibly updates the index (resetting it to the tree of ) and the working tree depending on . If is omitted, defaults to --mixed. The must be one of the following:

--soft Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

Error to run Android Studio

This is caused by having JAVA JRE installed as opposed to JAVA JDK.

The solution is simple:

sudo apt-get install openjdk-7-jdk

http://www.maxmakedesign.co.uk/development/2013/android-studio-tools-jar-classpath/

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

Automatically start a Windows Service on install

You can use the following command line to start the service:

net start *servicename*

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

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

T-SQL stored procedure that accepts multiple Id values

Try This One:

@list_of_params varchar(20) -- value 1, 2, 5, 7, 20 

SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id)  +'%')

very simple.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to move all HTML element children to another parent using JavaScript?

If you not use - in id's names then you can do this

_x000D_
_x000D_
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
    <span>Foo</span>_x000D_
    <b>Bar</b>_x000D_
    Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
_x000D_
_x000D_

How to pad a string to a fixed length with spaces in Python?

First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Facebook Login -> Settings -> Valid OAuth redirect URIs -> insert the domains of your redirect url, remember you should add 'https' or http. eg: if your redirect url is https://xxx.xxx.com/path/callback.do, you only need to enter https://xxx.xxx.com/, it's ok for me.

How do I check if file exists in jQuery or pure JavaScript?

A similar and more up-to-date approach.

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

File content into unix variable with newlines

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

ImportError: No module named Crypto.Cipher

This worked for me

pip install pycryptodome==3.4.3

How do I compile C++ with Clang?

Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:

To compile multiple C++ files using clang++:

$ clang++ *.cpp 
$ ./a.out 

To compile multiple C++ files using g++:

$ g++ -c *.cpp 
$ g++ -o temp.exe *.o
$ ./temp.exe

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

For me changing createLBPHFaceRecognizer() to

recognizer = cv2.face.LBPHFaceRecognizer_create()

fixed the problem

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
  loadXMLDoc(report,'responseTag');
  document.getElementById('responseTag').style.visibility='visible';
  document.getElementById('list_report').style.visibility='hidden';
  document.getElementById('formTag').style.visibility='hidden'; 
} 

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    document.getElementById('responseTag').style.visibility='visible';
    document.getElementById('list_report').style.visibility='hidden';
    document.getElementById('formTag').style.visibility='hidden'; 
  }); 
});

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    $('#responseTag').show();
    $('#list_report').hide();
    $('#formTag').hide(); 
  }); 
});

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

How can I take a screenshot with Selenium WebDriver?

Yes, it is possible to take a snapshot of a web page using Selenium WebDriver.

The getScreenshotAs() method provided by the WebDriver API does the work for us.

Syntax: getScreenshotAs(OutputType<X> target)

Return type: X

Parameters: target – Check the options provided by OutputType

Applicability: Not specific to any DOM element

Example:

TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);

Refer to the below working code snippet for more details.

public class TakeScreenShotDemo {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get(“http: //www.google.com”);

        TakesScreenshot screenshot = (TakesScreenshot) driver;

        File file = screenshot.getScreenshotAs(OutputType.FILE);

        // Creating a destination file
        File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
        try {
            FileUtils.copyFile(file, destination);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Visit Snapshot using WebDriver for getting more details.

How to convert a python numpy array to an RGB image with Opencv 2.4?

If anyone else simply wants to display a black image as a background, here e.g. for 500x500 px:

import cv2
import numpy as np

black_screen  = np.zeros([500,500,3])
cv2.imshow("Simple_black", black_screen)
cv2.waitKey(0)

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

trying to align html button at the center of the my page

Place it inside another div, use CSS to move the button to the middle:

<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
    <button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button> 
</div>?

Here is an example: JsFiddle

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

How many bytes in a JavaScript string?

String values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:

4.3.16 String Value

A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.

NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

Well if you have given

@ManyToOne ()
   @JoinColumn (name = "countryId")
   private Country country;

then object of that class i mean Country need to be save first.

because it will only allow User to get saved into the database if there is key available for the Country of that user for the same. means it will allow user to be saved if and only if that country is exist into the Country table.

So for that you need to save that Country first into the table.

DataSet panel (Report Data) in SSRS designer is gone

With a report (rdl) file selected in your solution, select View and then Report Data.

It is a shortcut of Ctrl+Alt+D.

enter image description here

Commenting out a set of lines in a shell script

: || {
your code here
your code here
your code here
your code here
}

IndentationError expected an indented block

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings.

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings.

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

Delete everything in a MongoDB database

Here are some useful delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete any particular collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

Way to insert text having ' (apostrophe) into a SQL table

yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.

(he doesn't work for me) must be => (he doesn''t work for me)

How to fire AJAX request Periodically?

I tried the below code,

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

This worked exactly as intended.

How to do a GitHub pull request

For those of us who have a github.com account, but only get a nasty error message when we type "git" into the command-line, here's how to do it all in your browser :)

  1. Same as Tim and Farhan wrote: Fork your own copy of the project: Step 1: Fork
  2. After a few seconds, you'll be redirected to your own forked copy of the project: Step 2
  3. Navigate to the file(s) you need to change and click "Edit this file" in the toolbar: Step 3: Edit a file
  4. After editing, write a few words describing the changes and then "Commit changes", just as well to the master branch (since this is only your own copy and not the "main" project). Step 4: Commit changes
  5. Repeat steps 3 and 4 for all files you need to edit, and then go back to the root of your copy of the project. There, click the green "Compare, review..." button: Step 5: Start submit
  6. Finally, click "Create pull request" ..and then "Create pull request" again after you've double-checked your request's heading and description: enter image description here

how to evenly distribute elements in a div next to each other?

I have managed to do it with the following css combination:

text-align: justify;
text-align-last: justify;
text-justify: inter-word;

Android Recyclerview vs ListView with Viewholder

If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.

So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.

Check if list<t> contains any of another list

You could use a nested Any() for this check which is available on any Enumerable:

bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));

Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet<T> so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

bool hasMatch = parameters.Select(x => x.source)
                          .Intersect(myStrings)
                          .Any(); 

Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

Best implementation for hashCode method for a collection

If I understand your question correctly, you have a custom collection class (i.e. a new class that extends from the Collection interface) and you want to implement the hashCode() method.

If your collection class extends AbstractList, then you don't have to worry about it, there is already an implementation of equals() and hashCode() that works by iterating through all the objects and adding their hashCodes() together.

   public int hashCode() {
      int hashCode = 1;
      Iterator i = iterator();
      while (i.hasNext()) {
        Object obj = i.next();
        hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
      }
  return hashCode;
   }

Now if what you want is the best way to calculate the hash code for a specific class, I normally use the ^ (bitwise exclusive or) operator to process all fields that I use in the equals method:

public int hashCode(){
   return intMember ^ (stringField != null ? stringField.hashCode() : 0);
}

setup android on eclipse but don't know SDK directory

The path to the SDK is:

C:\Users\USERNAME\AppData\Local\Android\sdk

This can be used in Eclipse after you replace USERNAME with your Windows user name.

How do I get a list of locked users in an Oracle database?

Found it!

SELECT username, 
       account_status
  FROM dba_users;

Is there any way to start with a POST request using Selenium?

Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.

Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.

Basically, using the driver.execute_script() you can send any javascript, including Ajax queries.

#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/

import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType

jquery = open("jquery.min.js", "r").read()
#print jquery

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"

capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)

driver = webdriver.PhantomJS(desired_capabilities=capabilities)

driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery

ajax_query = '''
            $.post( "post", {
                "a" : "%s",
                "b" : "%s"
            });
            ''' % (1,2)

ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query

result = driver.execute_script("return " + ajax_query)
#print result

#print driver.page_source

driver.close()

# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org


None
a=1&b=2  <<---- that is OK, is the data contained into the POST
None
'''

How to pass multiple values through command argument in Asp.net?

CommandArgument='<%#Eval("ScrapId").Tostring()+ Eval("UserId")%>
//added the comment function

Can you control how an SVG's stroke-width is drawn?

No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).

SVG proposed stroke-location example, from phrogz.net/SVG/stroke-location.svg

As I noted in the proposal,

  • you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and
  • you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.

Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.

Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.

Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

How to change line-ending settings

Line ending format used in OS

  • Windows: CR (Carriage Return \r) and LF (LineFeed \n) pair
  • OSX,Linux: LF (LineFeed \n)

We can configure git to auto-correct line ending formats for each OS in two ways.

  1. Git Global configuration
  2. Use .gitattributes file

Global Configuration

In Linux/OSX
git config --global core.autocrlf input

This will fix any CRLF to LF when you commit.

In Windows
git config --global core.autocrlf true

This will make sure when you checkout in windows, all LF will convert to CRLF

.gitattributes File

It is a good idea to keep a .gitattributes file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.

* text=auto

This will treat all files as text files and convert to OS's line ending on checkout and back to LF on commit automatically. If wanted to tell explicitly, then use

* text eol=crlf
* text eol=lf

First one is for checkout and second one is for commit.

*.jpg binary

Treat all .jpg images as binary files, regardless of path. So no conversion needed.

Or you can add path qualifiers:

my_path/**/*.jpg binary

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

How to create a multiline UITextfield?

If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.

CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = @"Tap to Edit";

[textField addSubview:tapEditLbl];

error: unknown type name ‘bool’

Somewhere in your code there is a line #include <string>. This by itself tells you that the program is written in C++. So using g++ is better than gcc.

For the missing library: you should look around in the file system if you can find a file called libl.so. Use the locate command, try /usr/lib, /usr/local/lib, /opt/flex/lib, or use the brute-force find / | grep /libl.

Once you have found the file, you have to add the directory to the compiler command line, for example:

g++ -o scan lex.yy.c -L/opt/flex/lib -ll

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Reference the handle of the associated control in its creator, like so:

Note: Be wary of this solution.If a control has a handle it is much slower to do things like set the size and location of it. This makes InitializeComponent much slower. A better solution is to not background anything before the control has a handle.

How can I change the app display name build with Flutter?

The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:

But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run.

Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.

So, I fixed this as follows:

Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.

Then everything should work in the flutter run way.

But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

What causes the Broken Pipe Error?

The current state of a socket is determined by 'keep-alive' activity. In your case, this is possible that when you are issuing the send call, the keep-alive activity tells that the socket is active and so the send call will write the required data (40 bytes) in to the buffer and returns without giving any error.

When you are sending a bigger chunk, the send call goes in to blocking state.

The send man page also confirms this:

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case

So, while blocking for the free available buffer, if the caller is notified (by keep-alive mechanism) that the other end is no more present, the send call will fail.

Predicting the exact scenario is difficult with the mentioned info, but I believe, this should be the reason for you problem.

How to store a command in a variable in a shell script?

Use eval:

x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.

How to uninstall Eclipse?

There is no automated uninstaller.

You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.

Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~ refers to the user home directory even on Windows.

Why is there no uninstaller?

According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.

How to quickly uninstall Eclipse

Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.

In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.

How to completely uninstall Eclipse

If you really want to remove Eclipse without leaving any traces, you have to manually delete

  • all desktop and start menu shortcuts
  • the installation directory (e.g. ~/eclipse/photon/)
  • the p2 bundle pool (which is often shared with other eclipse installations)

The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/).

If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/ directory.

Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/ contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.

How to delete all projects

If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata directory to get all Eclipse workspaces on your machine.

If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/ directory.

Setting timezone to UTC (0) in PHP

UTC is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set accepts one of the following values:

    $timezones=array(
    "America/Adak",
    "America/Argentina/Buenos_Aires",
    "America/Argentina/La_Rioja",
    "America/Argentina/San_Luis",
    "America/Atikokan",
    "America/Belem",
    "America/Boise",
    "America/Caracas",
    "America/Chihuahua",
    "America/Cuiaba",
    "America/Denver",
    "America/El_Salvador",
    "America/Godthab",
    "America/Guatemala",
    "America/Hermosillo",
    "America/Indiana/Tell_City",
    "America/Inuvik",
    "America/Kentucky/Louisville",
    "America/Lima",
    "America/Managua",
    "America/Mazatlan",
    "America/Mexico_City",
    "America/Montreal",
    "America/Nome",
    "America/Ojinaga",
    "America/Port-au-Prince",
    "America/Rainy_River",
    "America/Rio_Branco",
    "America/Santo_Domingo",
    "America/St_Barthelemy",
    "America/St_Vincent",
    "America/Tijuana",
    "America/Whitehorse",
    "America/Anchorage",
    "America/Argentina/Catamarca",
    "America/Argentina/Mendoza",
    "America/Argentina/Tucuman",
    "America/Atka",
    "America/Belize",
    "America/Buenos_Aires",
    "America/Catamarca",
    "America/Coral_Harbour",
    "America/Curacao",
    "America/Detroit",
    "America/Ensenada",
    "America/Goose_Bay",
    "America/Guayaquil",
    "America/Indiana/Indianapolis",
    "America/Indiana/Vevay",
    "America/Iqaluit",
    "America/Kentucky/Monticello",
    "America/Los_Angeles",
    "America/Manaus",
    "America/Mendoza",
    "America/Miquelon",
    "America/Montserrat",
    "America/Noronha",
    "America/Panama",
    "America/Port_of_Spain",
    "America/Rankin_Inlet",
    "America/Rosario",
    "America/Sao_Paulo",
    "America/St_Johns",
    "America/Swift_Current",
    "America/Toronto",
    "America/Winnipeg",
    "America/Anguilla",
    "America/Argentina/ComodRivadavia",
    "America/Argentina/Rio_Gallegos",
    "America/Argentina/Ushuaia",
    "America/Bahia",
    "America/Blanc-Sablon",
    "America/Cambridge_Bay",
    "America/Cayenne",
    "America/Cordoba",
    "America/Danmarkshavn",
    "America/Dominica",
    "America/Fort_Wayne",
    "America/Grand_Turk",
    "America/Guyana",
    "America/Indiana/Knox",
    "America/Indiana/Vincennes",
    "America/Jamaica",
    "America/Knox_IN",
    "America/Louisville",
    "America/Marigot",
    "America/Menominee",
    "America/Moncton",
    "America/Nassau",
    "America/North_Dakota/Beulah",
    "America/Pangnirtung",
    "America/Porto_Acre",
    "America/Recife",
    "America/Santa_Isabel",
    "America/Scoresbysund",
    "America/St_Kitts",
    "America/Tegucigalpa",
    "America/Tortola",
    "America/Yakutat",
    "America/Antigua",
    "America/Argentina/Cordoba",
    "America/Argentina/Salta",
    "America/Aruba",
    "America/Bahia_Banderas",
    "America/Boa_Vista",
    "America/Campo_Grande",
    "America/Cayman",
    "America/Costa_Rica",
    "America/Dawson",
    "America/Edmonton",
    "America/Fortaleza",
    "America/Grenada",
    "America/Halifax",
    "America/Indiana/Marengo",
    "America/Indiana/Winamac",
    "America/Jujuy",
    "America/Kralendijk",
    "America/Lower_Princes",
    "America/Martinique",
    "America/Merida",
    "America/Monterrey",
    "America/New_York",
    "America/North_Dakota/Center",
    "America/Paramaribo",
    "America/Porto_Velho",
    "America/Regina",
    "America/Santarem",
    "America/Shiprock",
    "America/St_Lucia",
    "America/Thule",
    "America/Vancouver",
    "America/Yellowknife",
    "America/Araguaina",
    "America/Argentina/Jujuy",
    "America/Argentina/San_Juan",
    "America/Asuncion",
    "America/Barbados",
    "America/Bogota",
    "America/Cancun",
    "America/Chicago",
    "America/Creston",
    "America/Dawson_Creek",
    "America/Eirunepe",
    "America/Glace_Bay",
    "America/Guadeloupe",
    "America/Havana",
    "America/Indiana/Petersburg",
    "America/Indianapolis",
    "America/Juneau",
    "America/La_Paz",
    "America/Maceio",
    "America/Matamoros",
    "America/Metlakatla",
    "America/Montevideo",
    "America/Nipigon",
    "America/North_Dakota/New_Salem",
    "America/Phoenix",
    "America/Puerto_Rico",
    "America/Resolute",
    "America/Santiago",
    "America/Sitka",
    "America/St_Thomas",
    "America/Thunder_Bay",
    "America/Virgin",
    "Indian/Antananarivo",
    "Indian/Kerguelen",
    "Indian/Reunion",
    "Australia/ACT",
    "Australia/Currie",
    "Australia/Lindeman",
    "Australia/Perth",
    "Australia/Victoria",
    "Europe/Amsterdam",
    "Europe/Berlin",
    "Europe/Chisinau",
    "Europe/Helsinki",
    "Europe/Kiev",
    "Europe/Madrid",
    "Europe/Moscow",
    "Europe/Prague",
    "Europe/Sarajevo",
    "Europe/Tallinn",
    "Europe/Vatican",
    "Europe/Zagreb",
    "Pacific/Apia",
    "Pacific/Efate",
    "Pacific/Galapagos",
    "Pacific/Johnston",
    "Pacific/Marquesas",
    "Pacific/Noumea",
    "Pacific/Ponape",
    "Pacific/Tahiti",
    "Pacific/Wallis",
    "Indian/Chagos",
    "Indian/Mahe",
    "Australia/Adelaide",
    "Australia/Darwin",
    "Australia/Lord_Howe",
    "Australia/Queensland",
    "Australia/West",
    "Europe/Andorra",
    "Europe/Bratislava",
    "Europe/Copenhagen",
    "Europe/Isle_of_Man",
    "Europe/Lisbon",
    "Europe/Malta",
    "Europe/Nicosia",
    "Europe/Riga",
    "Europe/Simferopol",
    "Europe/Tirane",
    "Europe/Vienna",
    "Europe/Zaporozhye",
    "Pacific/Auckland",
    "Pacific/Enderbury",
    "Pacific/Gambier",
    "Pacific/Kiritimati",
    "Pacific/Midway",
    "Pacific/Pago_Pago",
    "Pacific/Port_Moresby",
    "Pacific/Tarawa",
    "Pacific/Yap",
    "Africa/Abidjan",
    "Africa/Asmera",
    "Africa/Blantyre",
    "Africa/Ceuta",
    "Africa/Douala",
    "Africa/Johannesburg",
    "Africa/Kinshasa",
    "Africa/Lubumbashi",
    "Africa/Mbabane",
    "Africa/Niamey",
    "Africa/Timbuktu",
    "Africa/Accra",
    "Africa/Bamako",
    "Africa/Brazzaville",
    "Africa/Conakry",
    "Africa/El_Aaiun",
    "Africa/Juba",
    "Africa/Lagos",
    "Africa/Lusaka",
    "Africa/Mogadishu",
    "Africa/Nouakchott",
    "Africa/Tripoli",
    "Africa/Addis_Ababa",
    "Africa/Bangui",
    "Africa/Bujumbura",
    "Africa/Dakar",
    "Africa/Freetown",
    "Africa/Kampala",
    "Africa/Libreville",
    "Africa/Malabo",
    "Africa/Monrovia",
    "Africa/Ouagadougou",
    "Africa/Tunis",
    "Africa/Algiers",
    "Africa/Banjul",
    "Africa/Cairo",
    "Africa/Dar_es_Salaam",
    "Africa/Gaborone",
    "Africa/Khartoum",
    "Africa/Lome",
    "Africa/Maputo",
    "Africa/Nairobi",
    "Africa/Porto-Novo",
    "Africa/Windhoek",
    "Africa/Asmara",
    "Africa/Bissau",
    "Africa/Casablanca",
    "Africa/Djibouti",
    "Africa/Harare",
    "Africa/Kigali",
    "Africa/Luanda",
    "Africa/Maseru",
    "Africa/Ndjamena",
    "Africa/Sao_Tome",
    "Atlantic/Azores",
    "Atlantic/Faroe",
    "Atlantic/St_Helena",
    "Atlantic/Bermuda",
    "Atlantic/Jan_Mayen",
    "Atlantic/Stanley",
    "Atlantic/Canary",
    "Atlantic/Madeira",
    "Atlantic/Cape_Verde",
    "Atlantic/Reykjavik",
    "Atlantic/Faeroe",
    "Atlantic/South_Georgia",
    "Asia/Aden",
    "Asia/Aqtobe",
    "Asia/Baku",
    "Asia/Calcutta",
    "Asia/Dacca",
    "Asia/Dushanbe",
    "Asia/Hong_Kong",
    "Asia/Jayapura",
    "Asia/Kashgar",
    "Asia/Kuala_Lumpur",
    "Asia/Magadan",
    "Asia/Novokuznetsk",
    "Asia/Pontianak",
    "Asia/Riyadh",
    "Asia/Shanghai",
    "Asia/Tehran",
    "Asia/Ujung_Pandang",
    "Asia/Vladivostok",
    "Asia/Almaty",
    "Asia/Ashgabat",
    "Asia/Bangkok",
    "Asia/Choibalsan",
    "Asia/Damascus",
    "Asia/Gaza",
    "Asia/Hovd",
    "Asia/Jerusalem",
    "Asia/Kathmandu",
    "Asia/Kuching",
    "Asia/Makassar",
    "Asia/Novosibirsk",
    "Asia/Pyongyang",
    "Asia/Saigon",
    "Asia/Singapore",
    "Asia/Tel_Aviv",
    "Asia/Ulaanbaatar",
    "Asia/Yakutsk",
    "Asia/Amman",
    "Asia/Ashkhabad",
    "Asia/Beirut",
    "Asia/Chongqing",
    "Asia/Dhaka",
    "Asia/Harbin",
    "Asia/Irkutsk",
    "Asia/Kabul",
    "Asia/Katmandu",
    "Asia/Kuwait",
    "Asia/Manila",
    "Asia/Omsk",
    "Asia/Qatar",
    "Asia/Sakhalin",
    "Asia/Taipei",
    "Asia/Thimbu",
    "Asia/Ulan_Bator",
    "Asia/Yekaterinburg",
    "Asia/Anadyr",
    "Asia/Baghdad",
    "Asia/Bishkek",
    "Asia/Chungking",
    "Asia/Dili",
    "Asia/Hebron",
    "Asia/Istanbul",
    "Asia/Kamchatka",
    "Asia/Kolkata",
    "Asia/Macao",
    "Asia/Muscat",
    "Asia/Oral",
    "Asia/Qyzylorda",
    "Asia/Samarkand",
    "Asia/Tashkent",
    "Asia/Thimphu",
    "Asia/Urumqi",
    "Asia/Yerevan",
    "Asia/Aqtau",
    "Asia/Bahrain",
    "Asia/Brunei",
    "Asia/Colombo",
    "Asia/Dubai",
    "Asia/Ho_Chi_Minh",
    "Asia/Jakarta",
    "Asia/Karachi",
    "Asia/Krasnoyarsk",
    "Asia/Macau",
    "Asia/Nicosia",
    "Asia/Phnom_Penh",
    "Asia/Rangoon",
    "Asia/Seoul",
    "Asia/Tbilisi",
    "Asia/Tokyo",
    "Asia/Vientiane",
    "Australia/Canberra",
    "Australia/LHI",
    "Australia/NSW",
    "Australia/Tasmania",
    "Australia/Broken_Hill",
    "Australia/Hobart",
    "Australia/North",
    "Australia/Sydney",
    "Pacific/Chuuk",
    "Pacific/Fiji",
    "Pacific/Guam",
    "Pacific/Kwajalein",
    "Pacific/Niue",
    "Pacific/Pitcairn",
    "Pacific/Saipan",
    "Pacific/Truk",
    "Pacific/Chatham",
    "Pacific/Fakaofo",
    "Pacific/Guadalcanal",
    "Pacific/Kosrae",
    "Pacific/Nauru",
    "Pacific/Palau",
    "Pacific/Rarotonga",
    "Pacific/Tongatapu",
    "Pacific/Easter",
    "Pacific/Funafuti",
    "Pacific/Honolulu",
    "Pacific/Majuro",
    "Pacific/Norfolk",
    "Pacific/Pohnpei",
    "Pacific/Samoa",
    "Pacific/Wake",
    "Antarctica/Casey",
    "Antarctica/McMurdo",
    "Antarctica/Vostok",
    "Antarctica/Davis",
    "Antarctica/Palmer",
    "Antarctica/DumontDUrville",
    "Antarctica/Rothera",
    "Antarctica/Macquarie",
    "Antarctica/South_Pole",
    "Antarctica/Mawson",
    "Antarctica/Syowa",
    "Arctic/Longyearbyen",
    "Europe/Athens",
    "Europe/Brussels",
    "Europe/Dublin",
    "Europe/Istanbul",
    "Europe/Ljubljana",
    "Europe/Mariehamn",
    "Europe/Oslo",
    "Europe/Rome",
    "Europe/Skopje",
    "Europe/Tiraspol",
    "Europe/Vilnius",
    "Europe/Zurich",
    "Europe/Belfast",
    "Europe/Bucharest",
    "Europe/Gibraltar",
    "Europe/Jersey",
    "Europe/London",
    "Europe/Minsk",
    "Europe/Paris",
    "Europe/Samara",
    "Europe/Sofia",
    "Europe/Uzhgorod",
    "Europe/Volgograd",
    "Europe/Belgrade",
    "Europe/Budapest",
    "Europe/Guernsey",
    "Europe/Kaliningrad",
    "Europe/Luxembourg",
    "Europe/Monaco",
    "Europe/Podgorica",
    "Europe/San_Marino",
    "Europe/Stockholm",
    "Europe/Vaduz",
    "Europe/Warsaw",
    "Indian/Cocos",
    "Indian/Mauritius",
    "Indian/Christmas",
    "Indian/Maldives",
    "Indian/Comoro",
    "Indian/Mayotte",
    "Australia/Brisbane",
    "Australia/Eucla",
    "Australia/Melbourne",
    "Australia/South",
    "Australia/Yancowinna",
    );

Timezones in PHP at http://www.php.net/manual/en/timezones.php

proper way to sudo over ssh

echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost 
echo \"$varCommand\" | sudo bash

Attaching click to anchor tag in angular

You can use routerLink which is an alternative of href for angular 2.** Use routerLink as below in html

<a routerLink="/dashboard">My Link</a>

and make sure you register your routerLink in modules.ts or router.ts like this

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

How do I remove an object from an array with JavaScript?

If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:

const people = [
  { id: 1, name: 'serdar' },
  { id: 5, name: 'alex' },
  { id: 300, name: 'brittany' }
];

const idToRemove = 5;

const filteredPeople = people.filter((item) => item.id !== idToRemove);

// [
//   { id: 1, name: 'serdar' },
//   { id: 300, name: 'brittany' }
// [

Watch out though, filter() is non-mutating, so you'll get a new array back.

See the Mozilla Developer Network notes on Filter.

Replace all occurrences of a String using StringBuilder?

public static String replaceCharsNew(String replaceStr,Map<String,String> replaceStrMap){
        StringBuilder replaceStrBuilder = new StringBuilder(replaceStr);
        Set<String> keys=replaceStrMap.keySet();
        for(String invalidChar:keys){
            int index = -1;
            while((index=replaceStrBuilder.indexOf(invalidChar,index)) !=-1){
                replaceStrBuilder.replace(index,index+invalidChar.length(),replaceStrMap.get(invalidChar));
            }
        }
        return replaceStrBuilder.toString();
    }

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

right click on first file and select

enter image description here

then right click on second file and select

enter image description here

Screencast:

how to compare files in vscode

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

Double check that the foreign keys have exactly the same type as the field you've got in this table. For example, both should be Integer(10), or Varchar (8), even the number of characters.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

Conversion failed when converting the varchar value 'simple, ' to data type int

In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change

CONVERT(INT, CONVERT(VARCHAR(12), a.value))

To

CONVERT(INT,
        CASE
        WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
        ELSE 0 END) 

Basically this is saying if you cannot convert me to int assign value of 0 (in my example)

Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423

How do you clear the focus in javascript?

With jQuery its just: $(this).blur();

PHP Get name of current directory

$myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);

libs/images/index.php
Result: images

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

Write to .txt file?

FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Comparing double values in C#

Adding onto Valentin Kuzub's answer above:

we could use a single method that supports providing nth precision number:

public static bool EqualsNthDigitPrecision(this double value, double compareTo, int precisionPoint) =>
    Math.Abs(value - compareTo) < Math.Pow(10, -Math.Abs(precisionPoint));

Note: This method is built for simplicity without added bulk and not with performance in mind.

Foreign Key to non-primary key

Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.

The problem is, that if you have that problem, the database-schema is denormalized.

You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.

So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.

So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.

And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...

Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:

IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO




CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
     @in_RM_ApertureID uniqueidentifier 
    ,@in_DatumVon AS datetime 
    ,@in_DatumBis AS datetime 
    ,@in_Status AS integer 
) 
    RETURNS bit 
AS 
BEGIN   
    DECLARE @bNoCheckForThisCustomer AS bit 
    DECLARE @bIsInvalidValue AS bit 
    SET @bNoCheckForThisCustomer = 'false' 
    SET @bIsInvalidValue = 'false' 

    IF @in_Status = 99 
        RETURN 'false' 


    IF @in_DatumVon > @in_DatumBis 
    BEGIN 
        RETURN 'true' 
    END 


    IF @bNoCheckForThisCustomer = 'true'
        RETURN @bIsInvalidValue 


    IF NOT EXISTS
    ( 
        SELECT 
             T_Raum.RM_UID 
            ,T_Raum.RM_Status 
            ,T_Raum.RM_DatumVon 
            ,T_Raum.RM_DatumBis 
            ,T_Raum.RM_ApertureID 
        FROM T_Raum 
        WHERE (1=1) 
        AND T_Raum.RM_ApertureID = @in_RM_ApertureID 
        AND @in_DatumVon >= T_Raum.RM_DatumVon 
        AND @in_DatumBis <= T_Raum.RM_DatumBis 
        AND T_Raum.RM_Status <> 99  
    ) 
        SET @bIsInvalidValue = 'true' -- IF ! 

    RETURN @bIsInvalidValue 
END 



GO



IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]  
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
CHECK 
( 
    NOT 
    ( 
        dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1 
    ) 
) 
GO


IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]')) 
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
GO

How to configure heroku application DNS to Godaddy Domain?

Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS name to another DNS name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).

A CNAME record is for aliasing www.example.com -> www.example.com.herokudns.com.

You can't use CNAME for a naked domain (@), i.e. example.com (unless you find a name server that can do CNAME Flattening - which is what I did).

But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record that does this: www.example.com -> www.example.com.herokudns.com.

And then create a permanent 301 redirect from example.com to www.example.com.

This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com. @Jonathan Roy talks about this (above) but provides a bad link.

CSS: 100% font size - 100% of what?

My understanding is that when the font is set as follows

body {
  font-size: 100%;
}

the browser will render the font as per the user settings for that browser.

The spec says that % is rendered

relative to parent element's font size

http://www.w3.org/TR/CSS1/#font-size

In this case, I take that to mean what the browser is set to.

How can I clone a JavaScript object except for one key?

How about this:

let clone = Object.assign({}, value);
delete clone.unwantedKey;

How to differentiate single click event and double click event?

The behavior of the dblclick event is explained at Quirksmode.

The order of events for a dblclick is:

  1. mousedown
  2. mouseup
  3. click
  4. mousedown
  5. mouseup
  6. click
  7. dblclick

The one exception to this rule is (of course) Internet Explorer with their custom order of:

  1. mousedown
  2. mouseup
  3. click
  4. mouseup
  5. dblclick

As you can see, listening to both events together on the same element will result in extra calls to your click handler.

How to render a DateTime object in a Twig template

I know this is a pretty old question, but I found this question today, but the answers were not what I needed.

So here's what I needed.

If you, like me, are looking to display the current date in twig, you can use the following:

{{ "now"|date("m/d/Y") }}

See documentation about this:

date in twig

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

Sending mass email using PHP

Why don't you rather use phplist? It's also built on top of PHP Mailer and a lot of industry leaders are using it. I've used it myself a couple of times to send out bulk mails to my clients. The nice thing about phplist is that you can throttle your messages on a domain level plus a time limit level.

What we've also done with a couple of internal capture systems we've got was to push our user base to the mailling list and then have a cron entry triggering a given mail each day. The possibilities are endless, that's the awesome thing about open source!

Finding an elements XPath using IE Developer tool

This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62

Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?

Can I use break to exit multiple nested 'for' loops?

Just to add an explicit answer using lambdas:

  for (int i = 0; i < n1; ++i) {
    [&] {
      for (int j = 0; j < n2; ++j) {
        for (int k = 0; k < n3; ++k) {
          return; // yay we're breaking out of 2 loops here
        }
      }
    }();
  }

Of course this pattern has a certain limitations and obviously C++11 only but I think it's quite useful.

Immutable array in Java

Since Guava 22, from package com.google.common.primitives you can use three new classes, which have a lower memory footprint compared to ImmutableList.

They also have a builder. Example:

int size = 2;
ImmutableLongArray longArray = ImmutableLongArray.builder(size)
  .add(1L)
  .add(2L)
  .build();

or, if the size is known at compile-time:

ImmutableLongArray longArray = ImmutableLongArray.of(1L, 2L);

This is another way of getting an immutable view of an array for Java primitives.

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

milliseconds to days

int days = (int) (milliseconds / 86 400 000 )

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

Uninstall Django completely

I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.

SQL Error with Order By in Subquery

You don't need order by in your sub query. Move it out into the main query, and include the column you want to order by in the subquery.

however, your query is just returning a count, so I don't see the point of the order by.

Authenticate Jenkins CI for Github private repository

Perhaps GitHub's support for deploy keys is what you're looking for? To quote that page:

When should I use a deploy key?

Simple, when you have a server that needs pull access to a single private repo. This key is attached directly to the repository instead of to a personal user account.

If that's what you're already trying and it doesn't work, you might want to update your question with more details of the URLs being used, the names and location of the key files, etc.


Now for the technical part: How to use your SSH key with Jenkins?

If you have, say, a jenkins unix user, you can store your deploy key in ~/.ssh/id_rsa. When Jenkins tries to clone the repo via ssh, it will try to use that key.

In some setups, you cannot run Jenkins as an own user account, and possibly also cannot use the default ssh key location ~/.ssh/id_rsa. In such cases, you can create a key in a different location, e.g. ~/.ssh/deploy_key, and configure ssh to use that with an entry in ~/.ssh/config:

Host github-deploy-myproject
    HostName       github.com
    User           git
    IdentityFile   ~/.ssh/deploy_key
    IdentitiesOnly yes

Because all you authenticate to all Github repositories using [email protected] and you don't want the above key to be used for all your connections to Github, we created a host alias github-deploy-myproject. Your clone URL now becomes

git clone github-deploy-myproject:myuser/myproject

and that is also what you put as repository URL into Jenkins.

(Note that you must not put ssh:// in front in order for this to work.)

How do I output lists as a table in Jupyter notebook?

There is a nice trick: wrap the data with pandas DataFrame.

import pandas as pd
data = [[1, 2], [3, 4]]
pd.DataFrame(data, columns=["Foo", "Bar"])

It displays data like:

  | Foo | Bar |
0 | 1   | 2   |
1 | 3   | 4   |

What’s the best RESTful method to return total number of items in an object?

Alternative when you don't need actual items

Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.

but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:

/api/members?metaonly=true
/api/members?includeitems=0

or something similar...

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Try:

Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator).

https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-configuration

Reflection: How to Invoke Method with parameters

Change "methodInfo" to "classInstance", just like in the call with the null parameter array.

  result = methodInfo.Invoke(classInstance, parametersArray);

Windows 8.1 gets Error 720 on connect VPN

Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:

why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.

Solution:

  1. check write permissions on registers

    a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it

    b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log

    c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"

    d. run the following command netsh int ipv6 reset reset.log and repeat step c)

  2. unistall all not-working miniports

    a. go to device managers (windows+x -> device manager)

    b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)

    c. unistall these not working devices

    d. reboot your computer

    e. Repeat steps a) - d) until you will not see any yellow mark on miniports

  3. delete your vpn connection and create a new one.

that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)

references:

http://en.remontka.pro/error-720-windows-8-and-8-1-solved/

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Make a negative number positive

Try this in the for loop:

sum += Math.abs(arr[i])

long long int vs. long int vs. int64_t in C++

Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like

template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64

Error installing mysql2: Failed to build gem native extension

Another way for MacOS users

If you used "brew" to install mysql:

gem install mysql2 -v 'x.x.x' -- --with-mysql-config=/usr/local/Cellar/mysql/y.y.y/bin/mysql_config

x.x.x = version of the mysql2 gem you want to install
y.y.y = the version of mysql you have installed ls /usr/local/Cellar/mysql to find it.

Using Page_Load and Page_PreRender in ASP.Net

Well a big requirement to implement PreRender as opposed to Load is the need to work with the controls on the page. On Page_Load, the controls are not rendered, and therefore cannot be referenced.

Python exit commands - why so many and when should each be used?

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

    Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>
    

    This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

    Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  2. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

    Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>
    

    However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  3. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

    Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  4. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

    Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

Javascript: 'window' is not defined

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

Using a string variable as a variable name

You can use exec for that:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

Why can't Python parse this JSON data?

Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

Note: use json.loads instead of json.load. In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object.

To be honest, I don't think it's a problem to load all json data into memory in most cases. I see this in JS, Java, Kotlin, cpp, rust almost every language I use. Consider memory issue like a joke to me :)

On the other hand, I don't think you can parse json without reading all of it.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

Below code worked for me

set @@foreign_key_checks=0;
ALTER TABLE  `table1` ADD CONSTRAINT `table1_fk1` FOREIGN KEY (`coloumn`) REFERENCES `table2` (`id`) ON DELETE CASCADE;

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

React this.setState is not a function

Now in react with es6/7 you can bind function to current context with arrow function like this, make request and resolve promises like this :

listMovies = async () => {
 const request = await VK.api('users.get',{fields: 'photo_50'});
 const data = await request.json()
 if (data) {
  this.setState({movies: data})
 }
}

With this method you can easily call this function in the componentDidMount and wait the data before render your html in your render function.

I don't know the size of your project but I personally advise against using the current state of the component to manipulate datas. You should use external state like Redux or Flux or something else for that.