Programs & Examples On #Powerpack

How to write the code for the back button?

In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.

  function redirection()
        {
           <?php $send=$_SERVER['HTTP_REFERER'];?> 
            var redirect_to="<?php echo $send;?>";             
            window.location = redirect_to;

        }

What is the difference between max-device-width and max-width for mobile web?

the difference is that max-device-width is all screen's width and max-width means the space used by the browser to show the pages. But another important difference is the support of android browsers, in fact if u're going to use max-device-width this will work only in Opera, instead I'm sure that max-width will work for every kind of mobile browser (I had test it in Chrome, firefox and opera for ANDROID).

How can I do an UPDATE statement with JOIN in SQL Server?

MySQL

You'll get the best performance if you forget the where clause and place all conditions in the ON expression.

I think this is because the query first has to join the tables then runs the where clause on that, so if you can reduce what is required to join then that's the fasted way to get the results/do the udpate.

Example

Scenario

You have a table of users. They can log in using their username or email or account_number. These accounts can be active (1) or inactive (0). This table has 50000 rows

You then have a table of users to disable at one go because you find out they've all done something bad. This table however, has one column with usernames, emails and account numbers mixed. It also has a "has_run" indicator which needs to be set to 1 (true) when it has been run

Query

UPDATE users User
    INNER JOIN
        blacklist_users BlacklistUser
        ON
        (
            User.username = BlacklistUser.account_ref
            OR
            User.email = BlacklistedUser.account_ref
            OR
            User.phone_number = BlacklistUser.account_ref
            AND
            User.is_active = 1
            AND
            BlacklistUser.has_run = 0
        )
    SET
        User.is_active = 0,
        BlacklistUser.has_run = 1;

Reasoning

If we had to join on just the OR conditions it would essentially need to check each row 4 times to see if it should join, and potentially return a lot more rows. However, by giving it more conditions it can "skip" a lot of rows if they don't meet all the conditions when joining.

Bonus

It's more readable. All the conditions are in one place and the rows to update are in one place

Escaping single quote in PHP when inserting into MySQL

You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"

where $val is the data which is troubling you.

Jasmine.js comparing arrays

You can compare an array like the below mentioned if the array has some values

it('should check if the array are equal', function() {
        var mockArr = [1, 2, 3];
        expect(mockArr ).toEqual([1, 2, 3]);
 });

But if the array that is returned from some function has more than 1 elements and all are zero then verify by using

expect(mockArray[0]).toBe(0);

How to delete images from a private docker registry?

Another tool you can use is registry-cli. For example, this command:

registry.py -l "login:password" -r https://your-registry.example.com --delete

will delete all but the last 10 images.

Unicode characters in URLs

As all of these comments are true, you should note that as far as ICANN approved Arabic (Persian) and Chinese characters to be registered as Domain Name, all of the browser-making companies (Microsoft, Mozilla, Apple, etc.) have to support Unicode in URLs without any encoding, and those should be searchable by Google, etc.

So this issue will resolve ASAP.

Put request with simple string as request body

I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:

const request = axios.put(url, "\"" + values.guid + "\"", {
    headers: {
        "Accept": "application/json",
        "Content-type": "application/json",
        "Authorization": "Bearer " + sessionStorage.getItem('jwt')
    }
})

My webapi server method signature is this:

public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)

Polygon Drawing and Getting Coordinates with Google Map API v3

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});

Using boolean values in C

You can simply use the #define directive as follows:

#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;

And use as follows:

bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);

and so on

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

Make virtualenv inherit specific packages from your global site-packages

You can use the --system-site-packages and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

Eclipse error ... cannot be resolved to a type

Project -> Clean

can at least sometimes be sufficient to resolve the matter.

Need table of key codes for android and presenter

They are ASCII dec codes. A full table can be found here.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Regex match everything after question mark?

With the positive lookbehind technique:

(?<=\?).*

(We're searching for a text preceded by a question mark here)

Input: derpderp?mystring blahbeh
Output: mystring blahbeh

Example

Basically the ?<= is a group construct, that requires the escaped question-mark, before any match can be made.

They perform really well, but not all implementations support them.

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.

Within your database, locate the file_id of the log file using the following query.

SELECT * FROM sys.database_files;

In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.

DBCC LOGINFO;

Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.

If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.

-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;

This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.

What is the default initialization of an array in Java?

According to java,

Data Type - Default values

byte - 0

short - 0

int - 0

long - 0L

float - 0.0f

double - 0.0d

char - '\u0000'

String (or any object) - null

boolean - false

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

How to Multi-thread an Operation Within a Loop in Python

import numpy as np
import threading


def threaded_process(items_chunk):
    """ Your main process which runs in thread for each chunk"""
    for item in items_chunk:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')  

n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
    thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
    thread_list.append(thread)
    thread_list[thr].start()

for thread in thread_list:
    thread.join()

Identify if a string is a number

You can also use:

stringTest.All(char.IsDigit);

It will return true for all Numeric Digits (not float) and false if input string is any sort of alphanumeric.

Please note: stringTest should not be an empty string as this would pass the test of being numeric.

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

Find an element by class name, from a known parent element

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

How to support placeholder attribute in IE8 and 9

I used the code of this link http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html

But in browser detection I used:

if (navigator.userAgent.indexOf('MSIE') > -1) {
 //Your placeholder support code here...
}

Counting the number of option tags in a select tag in jQuery

The W3C solution:

var len = document.getElementById("input1").length;

Package opencv was not found in the pkg-config search path

I got the same error when trying to compile a Go package on Debian 9.8:

# pkg-config --cflags  -- libssl libcrypto
Package libssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libssl.pc'

The thing is that pkg-config searches for package meta-information in .pc files. Such files come from the dev package. So, even though I had libssl installed, I still got the error. It was resolved by running:

sudo apt-get install libssl-dev

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

Setting a div's height in HTML with CSS

The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.

HTML embed autoplay="false", but still plays automatically

None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed or object elements in HTML5. For video or audio elements they did stop autoplay. For embed and object they did not.

I tested this using the embed and object elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video or audio elements, just when using embed and object.

It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.

To do this in Firefox I have posted the settings below:

  1. Open up your Firefox Browser, click the menu button, and select "Options"
  2. Select the "Privacy & Security" panel and scroll down to the "Permissions" section
  3. Find "Autoplay" and click the "Settings" button. In the dropdown change it to block audio and video. The default is just audio.

Your videos will NOT autoplay now when displaying videos in web pages using object or embed elements.

How to format JSON in notepad++

You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.

This answer explains it pretty good: How to reformat JSON in Notepad++?

Failed linking file resources

This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project

How do I select the parent form based on which submit button is clicked?

To get the form that the submit is inside why not just

this.form

Easiest & quickest path to the result.

commands not found on zsh

A way to edit the .zshrc file without doing it through iTerm2 or native Terminal on macOS is to use a terminal in another application. For example, I used the terminal as part of VSCode and was able to find and edit the file.

How do I search a Perl array for a matching string?

For just a boolean match result or for a count of occurrences, you could use:

use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
    my $count=map {m/^$str$/i} @foo;
    if ($count) {
        print "I found '$str' $count time(s) in '$patterns'\n";
    } else {
        print "I could not find '$str' in the pattern list\n"
    };
}

Output:

I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'

Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.

Why do I need to override the equals and hashCode methods in Java?

class A {
    int i;
    // Hashing Algorithm
    if even number return 0 else return 1
    // Equals Algorithm,
    if i = this.i return true else false
}
  • put('key','value') will calculate the hash value using hashCode() to determine the bucket and uses equals() method to find whether the value is already present in the Bucket. If not it will added else it will be replaced with current value
  • get('key') will use hashCode() to find the Entry (bucket) first and equals() to find the value in Entry

if Both are overridden,

Map<A>

Map.Entry 1 --> 1,3,5,...
Map.Entry 2 --> 2,4,6,...

if equals is not overridden

Map<A>

Map.Entry 1 --> 1,3,5,...,1,3,5,... // Duplicate values as equals not overridden
Map.Entry 2 --> 2,4,6,...,2,4,..

If hashCode is not overridden

Map<A>

Map.Entry 1 --> 1
Map.Entry 2 --> 2
Map.Entry 3 --> 3
Map.Entry 4 --> 1
Map.Entry 5 --> 2
Map.Entry 6 --> 3 // Same values are Stored in different hasCodes violates Contract 1
So on...

HashCode Equal Contract

  1. Two keys equal according to equal method should generate same hashCode
  2. Two Keys generating same hashCode need not be equal (In above example all even numbers generate same hash Code)

Git keeps asking me for my ssh key passphrase

What worked for me on Windows was (I had cloned code from a repo 1st):

eval $(ssh-agent)
ssh-add 
git pull 

at which time it asked me one last time for my passphrase

Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

Json.NET does this...

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");

string json = JsonConvert.SerializeObject(values);
// {
//   "key1": "value1",
//   "key2": "value2"
// }

More examples: Serializing Collections with Json.NET

Javascript logical "!==" operator?

The !== opererator tests whether values are not equal or not the same type. i.e.

var x = 5;
var y = '5';
var 1 = y !== x; // true
var 2 = y != x; // false

How to convert comma-separated String to List?

Here is another one for converting CSV to ArrayList:

String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
    System.out.println(" -->"+aList.get(i));
}

Prints you

-->string
-->with
-->comma

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

HttpUtility does not exist in the current context

Adding a reference to Sysem.Web.Dll did it for me.

Collapsing Sidebar with Bootstrap

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

https://codeply.com/p/esYgHWB2zJ

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  }
  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -41.6%;
  }

  .row-offcanvas-left
  .sidebar-offcanvas {
    left: -41.6%;
  }
  .row-offcanvas-right.active {
    right: 41.6%;
  }
  .row-offcanvas-left.active {
    left: 41.6%;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  }
  #sidebar {
    padding-top:0;
  }
}

Also, there are several more Bootstrap sidebar examples here


Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Html.Textbox VS Html.TextboxFor

Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Does your HOSTS file have an entry for localhost? Some other situations this error is seen in seem to have this as a problem resolution.

Make sure you have 127.0.0.1 localhost set in it...

(from this and this)

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

How can I check if a program exists from a Bash script?

Try using:

test -x filename

or

[ -x filename ]

From the Bash manpage under Conditional Expressions:

 -x file
          True if file exists and is executable.

"git rebase origin" vs."git rebase origin/master"

Here's a better option:

git remote set-head -a origin

From the documentation:

With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.

This has actually been around quite a while (since v1.6.3); not sure how I missed it!

How is __eq__ handled in Python and in what order?

When Python2.x sees a == b, it tries the following.

  • If type(b) is a new-style class, and type(b) is a subclass of type(a), and type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If type(a) has overridden __eq__ (that is, type(a).__eq__ isn't object.__eq__), then the result is a.__eq__(b).
  • If type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If none of the above are the case, Python repeats the process looking for __cmp__. If it exists, the objects are equal iff it returns zero.
  • As a final fallback, Python calls object.__eq__(a, b), which is True iff a and b are the same object.

If any of the special methods return NotImplemented, Python acts as though the method didn't exist.

Note that last step carefully: if neither a nor b overloads ==, then a == b is the same as a is b.


From https://eev.ee/blog/2012/03/24/python-faq-equality/

How to set commands output as a variable in a batch file

in a single line:

FOR /F "tokens=*" %%g IN ('*your command*') do (SET VAR=%%g)

the command output will be set in %g then in VAR.

More informations: https://ss64.com/nt/for_cmd.html

How to set top position using jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

How to get temporary folder for current user

try

Environment.GetEnvironmentVariable("temp");

HashMap with multiple values under the same key

We can create a class to have multiple keys or values and the object of this class can be used as a parameter in map. You can refer to https://stackoverflow.com/a/44181931/8065321

How do I append a node to an existing XML file in java

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class AddXmlNode {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("server.xml");
        Element root = document.getDocumentElement();

        Collection<Server> servers = new ArrayList<Server>();
        servers.add(new Server());

        for (Server server : servers) {
            // server elements
            Element newServer = document.createElement("server");

            Element name = document.createElement("name");
            name.appendChild(document.createTextNode(server.getName()));
            newServer.appendChild(name);

            Element port = document.createElement("port");
            port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
            newServer.appendChild(port);

            root.appendChild(newServer);
        }

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult("server.xml");
        transformer.transform(source, result);
    }

    public static class Server {
        public String getName() { return "foo"; }
        public Integer getPort() { return 12345; }
    }
}

Example server.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
  <server>
    <name>something</name>
    <port>port</port>
  </server>
</Servers>

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

git commit error: pathspec 'commit' did not match any file(s) known to git

I figured out mistake here use double quotations instead of single quotations.

change this

git commit -m 'initial commit'

to

git commit -m "initial commit"

What is the .idea folder?

It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore file:

# intellij configs
.idea/

How to run function of parent window when child window closes?

I know this post is old, but I found that this really works well:

window.onunload = function() {
    window.opener.location.href = window.opener.location.href;
};

The window.onunload part was the hint I found googling this page. Thanks, @jerjer!

Curl to return http status code along with the response

Append a line "http_code:200" at the end, and then grep for the keyword "http_code:" and extract the response code.

result=$(curl -w "\nhttp_code:%{http_code}" http://localhost)

echo "result: ${result}"   #the curl result with "http_code:" at the end

http_code=$(echo "${result}" | grep 'http_code:' | sed 's/http_code://g') 

echo "HTTP_CODE: ${http_code}"  #the http response code

In this case, you can still use the non-silent mode / verbose mode to get more information about the request such as the curl response body.

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

How to get file_get_contents() to work with HTTPS?

$url= 'https://example.com';

$arrContextOptions=array(
      "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    );  

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

This will allow you to get the content from the url whether it is a HTTPS

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

I just had the same problem, but none of these answers helped me. I did find the dll on my pc in the location Mostey noted: (C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll), but this is not the one that was referenced in the project I was trying to get building.

The reference in our project in Visual Studio 2012 was pointing to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\. This location was empty for me, but it worked fine for everyone else. It took a number of tries, but I finally tracked down a working installer. I hope this saves others the same hassle!

--> Office Tools Bundle installer for VS2012 <--

This was located on the Office Documentation and Download page. Scroll down to Tools Downloads. There's also currently one for VS2013.

Move to another EditText when Soft Keyboard Next is clicked on Android

In some cases you may need to move the focus to the next field manually :

focusSearch(FOCUS_DOWN).requestFocus();

You might need this if, for example, you have a text field that opens a date picker on click, and you want the focus to automatically move to the next input field once a date is selected by the user and the picker closes. There's no way to handle this in XML, it has to be done programmatically.

Send raw ZPL to Zebra printer via USB

Found amazing simple solution - working for Chrome (Windows, not tested on Mac)

Zebra ZP 450

  1. Go here Zebra Generic Text
  2. Go precisely by the manual
  3. No COM1 or any other ports needed - USB is enough
  4. When done (named the printer ZTEXT), does not matter if it won't print a test page
  5. Turn of Spooling and enable direct printing in Printer Preferences - 1 note here 1 printer is ZP450 CPT and other ZP450 only - on the other one I do not even need to turn off spooling and it worked.
  6. Go to Chrome and printing ZPL from there with Chrome Print Dialog Box by selecting the ZTEXT printer (Generic / Text) Printer (Do not choose Windows Dialog Box) - we needed this for Chrome to be working

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

XmlSerializer giving FileNotFoundException at constructor

I was getting the same error, and it was due to the type I was trying to deserialize not having a default parameterless constructor. I added a constructor, and it started working.

Cmake doesn't find Boost

I had the same problem, and none of the above solutions worked. Actually, the file include/boost/version.hpp could not be read (by the cmake script launched by jenkins).

I had to manually change the permission of the (boost) library (even though jenkins belongs to the group, but that is another problem linked to jenkins that I could not figure out):

chmod o+wx ${BOOST_ROOT} -R # allow reading/execution on the whole library
#chmod g+wx ${BOOST_ROOT} -R # this did not suffice, strangely, but it is another story I guess

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

An existing connection was forcibly closed by the remote host - WCF

I have seen this once. Are the users requesting different amounts of data? I found that even if you can configure a binding for data payloads (i.e. maxReceivedMessageSize), the httpRuntime maxRequestLength trumps the WCF setting, so if IIS is trying to serve a request that exceeds that, it exhibits this behavior.

Think of it like this:

If maxReceivedMessageSize is 12MB in your WCF behavior, and maxRequestLength is 4MB (default), IIS wins.

How to atomically delete keys matching a pattern using Redis

You can also use this command to delete the keys:-

Suppose there are many types of keys in your redis like-

  1. 'xyz_category_fpc_12'
  2. 'xyz_category_fpc_245'
  3. 'xyz_category_fpc_321'
  4. 'xyz_product_fpc_876'
  5. 'xyz_product_fpc_302'
  6. 'xyz_product_fpc_01232'

Ex- 'xyz_category_fpc' here xyz is a sitename, and these keys are related to products and categories of a E-Commerce site and generated by FPC.

If you use this command as below-

redis-cli --scan --pattern 'key*' | xargs redis-cli del

OR

redis-cli --scan --pattern 'xyz_category_fpc*' | xargs redis-cli del

It deletes all the keys like 'xyz_category_fpc' (delete 1, 2 and 3 keys). For delete other 4, 5 and 6 number keys use 'xyz_product_fpc' in above command.

If you want to Delete Everything in Redis, then follow these Commands-

With redis-cli:

  1. FLUSHDB - Removes data from your connection's CURRENT database.
  2. FLUSHALL - Removes data from ALL databases.

For Example:- in your shell:

redis-cli flushall
redis-cli flushdb

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

How to create a HTML Table from a PHP array?

Possibly your most versatile approach is to select a templating system.

Can I call a constructor from another constructor (do constructor chaining) in C++?

If I understand your question correctly, you're asking if you can call multiple constructors in C++?

If that's what you're looking for, then no - that is not possible.

You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.

You can even have one constructor with defaulted arguments on the end.

But you may not have multiple constructors, and then call each of them separately.

How to redirect the output of the time command to a file in Linux?

&>out time command >/dev/null

in your case

&>out time sleep 1 >/dev/null

then

cat out

Maven does not find JUnit tests to run

By default Maven uses the following naming conventions when looking for tests to run:

If your test class doesn't follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.

html5 - canvas element - Multiple layers

I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.

So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.

https://github.com/federicojacobi/layeredCanvas

I intend to add extra capabilities, but for now it will do.

You can do multiple functions and call them in order to "fake" layers.

Maven dependency for Servlet 3.0 API?

Just for newcomers.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

CSS Image size, how to fill, but not stretch?

  • Not using css background
  • Only 1 div to clip it
  • Resized to minimum width than keep correct aspect ratio
  • Crop from center (vertically and horizontally, you can adjust that with the top, lef & transform)

Be careful if you're using a theme or something, they'll often declare img max-width at 100%. You got to make none. Test it out :)

https://jsfiddle.net/o63u8sh4/

<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>

<p>Wrapped:</p>
<div>
    <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>


div{
  width:150px; 
  height:100px; 
  position:relative;
  overflow:hidden;
}
div img{
  min-width:100%;
  min-height:100%;
  height:auto;
  position:relative;
  top:50%;
  left:50%;
  transform:translateY(-50%) translateX(-50%);
}

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

Cookie blocked/not saved in IFRAME in Internet Explorer

In Rails I am using this gem : https://github.com/merchii/rack-iframe Bawically it sets a set of abbreviations without a reference file: https://github.com/merchii/rack-iframe/blob/master/lib/rack/iframe.rb#L8

It is easy to install when you dont care at all about the meaning of the p3p stuff.

What is the use of the @Temporal annotation in Hibernate?

@Temporal is a JPA annotation which can be used to store in the database table on of the following column items:

  1. DATE (java.sql.Date)
  2. TIME (java.sql.Time)
  3. TIMESTAMP (java.sql.Timestamp)

Generally when we declare a Date field in the class and try to store it.
It will store as TIMESTAMP in the database.

@Temporal
private Date joinedDate;

Above code will store value looks like 08-07-17 04:33:35.870000000 PM

If we want to store only the DATE in the database,
We can use/define TemporalType.

@Temporal(TemporalType.DATE)
private Date joinedDate;

This time, it would store 08-07-17 in database

There are some other attributes as well as @Temporal which can be used based on the requirement.

Print execution time of a shell command

For a line-by-line delta measurement, try gnonom.

It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.

gnomon demo

Drop default constraint on a column in TSQL

This is how you would drop the constraint

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
   DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO

With a script

-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

set @database = 'dotnetnuke'
set @table = 'tabs'

DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
    where    constraint_catalog = @database and 
            table_name = @table
    exec    sp_executesql @sql
END

Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx

How do I add a resources folder to my Java project in Eclipse

Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder

CSS: fixed position on x-axis but not y?

If your block is originally positioned as static, you may want to try this

_x000D_
_x000D_
$(window).on('scroll', function () {_x000D_
_x000D_
  var $w = $(window);_x000D_
  $('.position-fixed-x').css('left', $w.scrollLeft());_x000D_
  $('.position-fixed-y').css('top', $w.scrollTop());_x000D_
_x000D_
});
_x000D_
.container {_x000D_
  width: 1000px;_x000D_
}_x000D_
_x000D_
.position-fixed-x {_x000D_
  position: relative; _x000D_
}_x000D_
_x000D_
.position-fixed-y {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.blue-box {_x000D_
  background:blue;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.red-box {_x000D_
  background: red;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
_x000D_
<div class="position-fixed-y red-box">_x000D_
  _x000D_
</div>_x000D_
_x000D_
The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do._x000D_
_x000D_
<div class="position-fixed-x blue-box">_x000D_
  _x000D_
</div>_x000D_
_x000D_
DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA._x000D_
_x000D_
The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring._x000D_
  _x000D_
 The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer._x000D_
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!_x000D_
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism)._x000D_
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein._x000D_
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created._x000D_
</div>
_x000D_
_x000D_
_x000D_

Trying to load local JSON file to show data in a html page using JQuery

You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>

data.js:

var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}

How to create a GUID in Excel?

The formula for German Excel:

=KLEIN(
    VERKETTEN(
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);"-";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));4);"-";"4";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
        DEZINHEX(ZUFALLSBEREICH(8;11));
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));
    )
)

Spring cannot find bean xml configuration file when it does exist

use it ApplicationContext context = new FileSystemXmlApplicationContext("Beans.xml");

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set your PRIMARY KEY as AUTO_INCREMENT.

Can a normal Class implement multiple interfaces?

Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.

Ceremonial example:

enter image description here

public interface Mammal {
    void move();
    boolean possessIntelligence();
}
public interface Animal extends Mammal {
    void liveInJungle();
}

public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
    void liveInCivilization();
}
public interface Carnivore {
    void eatMeat();
}
public interface Herbivore {
    void eatPlant();
}
public interface Omnivore extends Carnivore, Herbivore {
    void eatBothMeatAndPlant();
}
public interface FourLeggedMammal {
    void moveWithFourLegs();
}
public interface TwoLeggedMammal {
    void moveWithTwoLegs();
}
public interface Hunter {
    void huntForFood();
}
public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
    @Override
    public void liveInJungle() {
        System.out.println("I live in Outback country");
    }

    @Override
    public void move() {
        moveWithTwoLegs();
    }

    @Override
    public void moveWithTwoLegs() {
        System.out.println("I like to jump");
    }

    @Override
    public void eat() {
        eatPlant();
    }

    @Override
    public void eatPlant() {
        System.out.println("I like this grass");
    }

    @Override
    public boolean possessIntelligence() {
        return false;
    }
}

public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
    @Override
    public void liveInJungle() {
        System.out.println("I am king of the jungle!");

    }

    @Override
    public void move() {
        moveWithFourLegs();
    }

    @Override
    public void moveWithFourLegs() {
        System.out.println("I like to run sometimes.");
    }

    @Override
    public void eat() {
        eatMeat();
    }

    @Override
    public void eatMeat() {
        System.out.println("I like deer meat");
    }

    @Override
    public boolean possessIntelligence() {
        return false;
    }

    @Override
    public void huntForFood() {
        System.out.println("My females hunt often");
    }
}
public class Teacher implements Human {
    @Override
    public void liveInCivilization() {
        System.out.println("I live in an apartment");
    }

    @Override
    public void moveWithTwoLegs() {
        System.out.println("I wear shoes and walk with two legs one in front of the other");
    }

    @Override
    public void move() {
        moveWithTwoLegs();
    }

    @Override
    public boolean possessIntelligence() {
        return true;
    }

    @Override
    public void huntForFood() {
        System.out.println("My ancestors used to but now I mostly rely on cattle");
    }

    @Override
    public void eat() {
        eatBothMeatAndPlant();
    }

    @Override
    public void eatBothMeatAndPlant() {
        eatPlant();
        eatMeat();
    }

    @Override
    public void eatMeat() {
        System.out.println("I like this bacon");
    }

    @Override
    public void eatPlant() {
        System.out.println("I like this broccoli");
    }
}

How can I get the console logs from the iOS Simulator?

You can see the Simulator console window, including Safari Web Inspector and all the Web Development Tools by using the Safari Technology Preview app. Open your page in Safari on the Simulator and then go to Safari Technology Preview > Develop > Simulator.

Web Development Tools

How do I get the current absolute URL in Ruby on Rails?

For Rails 3.x and up:

#{request.protocol}#{request.host_with_port}#{request.fullpath}

For Rails 3.2 and up:

request.original_url

Because in rails 3.2 and up:

request.original_url = request.base_url + request.original_fullpath

For more info, plese visit http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url

How to show live preview in a small popup of linked page on mouse over on link?

Another way is to use a website thumbnail/link preview service LinkPeek (even happens to show a screenshot of StackOverflow as a demo right now), URL2PNG, Browshot, Websnapr, or an alternative.

Setting up a cron job in Windows

The windows equivalent to a cron job is a scheduled task.

A scheduled task can be created as described by Alex and Rudu, but it can also be done command line with schtasks (if you for instance need to script it or add it to version control).

An example:

schtasks /create /tn calculate /tr calc /sc weekly /d MON /st 06:05 /ru "System"

Creates the task calculate, which starts the calculator(calc) every monday at 6:05 (should you ever need that.)

All available commands can be found here: http://technet.microsoft.com/en-us/library/cc772785%28WS.10%29.aspx

It works on windows server 2008 as well as windows server 2003.

Which port(s) does XMPP use?

The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.

File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)

Jquery If radio button is checked

Try this:

if ( jQuery('#postageyes').is(':checked') ){ ... }

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

Git commit in terminal opens VIM, but can't get back to terminal

This is in answer to your question...

I'd also like to know how to make it open up in Sublime Text 2 instead

For Windows:

git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"

Check that the path for sublime_text.exe is correct and adjust if needed.

For Mac/Linux:

git config --global core.editor "subl -n -w"

If you get an error message such as:

error: There was a problem with the editor 'subl -n -w'.

Create the alias for subl

sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Again check that the path matches for your machine.

For Sublime Text simply save cmd S and close the window cmd W to return to git.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can do something like this :

<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Although I use the following code.

.carousel.fade
{
    opacity: 1;

    .item
    {
        -moz-transition: opacity ease-in-out .7s;
        -o-transition: opacity ease-in-out .7s;
        -webkit-transition: opacity ease-in-out .7s;
        transition: opacity ease-in-out .7s;
        left: 0 !important;
        opacity: 0;
        top:0;
        position:absolute;
        width: 100%;
        display:block !important;
        z-index:1;
        &:first-child{
            top:auto;
            position:relative;
        }

        &.active
        {
            opacity: 1;
            -moz-transition: opacity ease-in-out .7s;
            -o-transition: opacity ease-in-out .7s;
            -webkit-transition: opacity ease-in-out .7s;
            transition: opacity ease-in-out .7s;
            z-index:2;
        }
    }
}

Then change the class on the carousel from "carousel slide" to "carousel fade". This works in safari, chrome, firefox, and IE 10. It will correctly downgrade in IE 9, however, the nice face effect doesn't happen.

Edit: Since this answer has gotten so popular I've added the following which rewritten as pure CSS instead of the above which was LESS:

.carousel.fade {
  opacity: 1;
}
.carousel.fade .item {
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  left: 0 !important;
  opacity: 0;
  top:0;
  position:absolute;
  width: 100%;
  display:block !important;
  z-index:1;
}
.carousel.fade .item:first-child {
  top:auto;
  position:relative;
}
.carousel.fade .item.active {
  opacity: 1;
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  z-index:2;
}

How to install pip with Python 3?

Assuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages...

I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post. I had do quite a bit of Googling to make this work.

  1. Decide if you are using python (python2) or python3 and set your PATH correctly. (I am strictly a python3 user.) All commands below can substitute python3 for python if you are python2 user.
  2. wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
  3. tar -xzvf virtualenv-x.y.z.tar.gz
  4. python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
  5. source /path/to/new/virtualenv/bin/activate
    • Assumes you are using a Bourne-compatible shell, e.g., bash
    • Brilliantly, this virtualenv package includes a standalone version of pip and setuptools that are auto-magically installed into each new virtualenv. This solves the chicken and egg problem.
    • You may want to create an alias (or update your ~/.bashrc, etc.) for this final command to activate the python virtualenv during each login. It can be a pain to remember all these paths and commands.
  6. Check your version of python now: which python3 should give: /path/to/new/virtualenv/bin/python3
  7. Check pip is also available in the virtualenv via which pip... should give: /path/to/new/virtualenv/bin/pip

Then... pip, pip, pip!

Final tip to newbie Pythoneers: You don't think you need virtualenv when you start, but you will be happy to have it later. Helps with "what if" installation / upgrade scenarios for open source / shared packages.

Ref: https://virtualenv.pypa.io/en/latest/installation.html

Automatically deleting related rows in Laravel (Eloquent ORM)

As of Laravel 5.2, the documentation states that these kinds of event handlers should be registered in the AppServiceProvider:

<?php
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::deleting(function ($user) {
            $user->photos()->delete();
        });
    }

I even suppose to move them to separate classes instead of closures for better application structure.

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

Speed up rsync with Simultaneous/Concurrent File Transfers?

Have you tried using rclone.org?

With rclone you could do something like

rclone copy "${source}/${subfolder}/" "${target}/${subfolder}/" --progress --multi-thread-streams=N

where --multi-thread-streams=N represents the number of threads you wish to spawn.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

How can I refresh c# dataGridView after update ?

I know i am late to the party but hope this helps someone who will do the same with Class binding

var newEntry = new MyClassObject();

var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;

dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();

Converting Varchar Value to Integer/Decimal Value in SQL Server

The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2), it should work

 SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table

OR

 SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table

How do I restart a program based on user input?

Here's a fun way to do it with a decorator:

def restartable(func):
    def wrapper(*args,**kwargs):
        answer = 'y'
        while answer == 'y':
            func(*args,**kwargs)
            while True:
                answer = raw_input('Restart?  y/n:')
                if answer in ('y','n'):
                    break
                else:
                    print "invalid answer"
    return wrapper

@restartable
def main():
    print "foo"

main()

Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y' and keep running the code until the answer isn't 'y'.

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Uninstalling an MSI file from the command line without using msiexec

wmic product get name

Just gets the cmd stuck... still flashing _ after a couple minutes

in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x

Windows equivalent of OS X Keychain?

The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)

Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.

It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.

Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.

How can I access "static" class variables within class methods in Python?

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob 
WHERE fileid NOT IN 
       (SELECT id 
        FROM files 
        WHERE id is NOT NULL/*This line is unlikely to be needed 
                               but using NOT IN...*/
      )

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

how to permit an array with strong parameters

I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:

filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]

This works:

params.require(:model).permit(filters: [[:name, values: []]])

async for loop in node.js

Node.js introduced async await in 7.6 so this makes Javascript more beautiful.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
  var query = config[key].query;
  results.push(await search(query));
}
res.writeHead( ... );
res.end(results);

For this to work search fucntion has to return a promise or it has to be async function

If it is not returning a Promise you can help it to return a Promise

function asyncSearch(query) {
  return new Promise((resolve, reject) => {
   search(query,(result)=>{
    resolve(result);
   })
  })
}

Then replace this line await search(query); by await asyncSearch(query);

List passed by ref - help me explain this behaviour

There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.

When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.

Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)

double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m =  sum / v.size();

double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
    accum += (d - m) * (d - m);
});

double stdev = sqrt(accum / (v.size()-1));

Free tool to Create/Edit PNG Images?

The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).

How to set Default Controller in asp.net MVC 4 & MVC 5

In case you have only one controller and you want to access every action on root you can skip controller name like this

routes.MapRoute(
        "Default", 
        "{action}/{id}", 
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

unable to install pg gem

On macOS (El Capitan). You can simply use: brew install postgresql

C++ printing spaces or tabs given a user input integer

cout << "Enter amount of spaces you would like (integer)" << endl; 
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
   cout << " " ;
}
cout <<endl;

java.net.SocketException: Connection reset

There are several possible causes.

  1. The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.

  2. More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.

  3. It can also be caused by closing a socket when there is unread data in the socket receive buffer.

  4. In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

How to set the timeout for a TcpClient?

Set ReadTimeout or WriteTimeout property on the NetworkStream for synchronous reads/writes. Updating OP's code:

try
{
    TcpClient client = new TcpClient("remotehost", this.Port);
    Byte[] data = System.Text.Encoding.Unicode.GetBytes(this.Message);
    NetworkStream stream = client.GetStream();
    stream.WriteTimeout = 1000; //  <------- 1 second timeout
    stream.ReadTimeout = 1000; //  <------- 1 second timeout
    stream.Write(data, 0, data.Length);
    data = new Byte[512];
    Int32 bytes = stream.Read(data, 0, data.Length);
    this.Response = System.Text.Encoding.Unicode.GetString(data, 0, bytes);

    stream.Close();
    client.Close();    

    FireSentEvent();  //Notifies of success
}
catch (Exception ex)
{
    // Throws IOException on stream read/write timeout
    FireFailedEvent(ex); //Notifies of failure
}

Test if registry value exists

One-liner:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName

Only read selected columns

The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

Column selection (col_select)

The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().

Select columns by name
data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr  [ 4]: carrier, tailnum, origin, dest
#> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
#>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
#>  1 N142…  2013     1     1      517            515         2      830
#>  2 N242…  2013     1     1      533            529         4      850
#>  3 N619…  2013     1     1      542            540         2      923
#>  4 N804…  2013     1     1      544            545        -1     1004
#>  5 N668…  2013     1     1      554            600        -6      812
#>  6 N394…  2013     1     1      554            558        -4      740
#>  7 N516…  2013     1     1      555            600        -5      913
#>  8 N829…  2013     1     1      557            600        -3      709
#>  9 N593…  2013     1     1      557            600        -3      838
#> 10 N3AL…  2013     1     1      558            600        -2      753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> #   time_hour <dttm>

How do I sort a vector of pairs based on the second element of the pair?

EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

Just use a custom comparator (it's an optional 3rd argument to std::sort)

struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

Double array initialization in Java

If you can accept Double Objects than this post is helpful: Initialization of an ArrayList in one line

List<Double> y = Arrays.asList(null, 1.0, 2.0);
Double x = y.get(1);

Initializing multiple variables to the same value in Java

I do not think that is possible you have to set all the values individualling (like the first example you provided.)

The Second example you gave, will only Initialize the last varuable to "" and not the others.

Arrays.fill with multidimensional array in Java

Arrays.fill works with single dimensional array, so to fill two dimensional array we can do below

for (int i = 0, len = arr.length; i < len; i++)
    Arrays.fill(arr[i], 0);

How to select all records from one table that do not exist in another table?

SELECT <column_list>
FROM TABLEA a
LEFTJOIN TABLEB b 
ON a.Key = b.Key 
WHERE b.Key IS NULL;

enter image description here

https://www.cloudways.com/blog/how-to-join-two-tables-mysql/

Kotlin - How to correctly concatenate a String

I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.

// A list may come from an API JSON like
{
   "names": [
      "Person 1",
      "Person 2",
      "Person 3",
         ...
      "Person N"
   ]
}
var listOfNames = mutableListOf<String>() 

val stringOfNames = listOfNames.joinToString(", ") 
// ", " <- a separator for the strings, could be any string that you want

// Posible result
// Person 1, Person 2, Person 3, ..., Person N

This is useful for concatenating list of strings with separator.

PHP Get all subdirectories of a given directory

You can use the glob() function to do this.

Here is some documentation on it: http://php.net/manual/en/function.glob.php

Get querystring from URL using jQuery

To retrieve the entire querystring from the current URL, beginning with the ? character, you can use

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

Example:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }

  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

You can use the above like so:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') { 
  console.log(urlParams.parameterName);
}

ERROR 1148: The used command is not allowed with this MySQL version

The top answers are correct. Please check them direct in MySQL CLI first. If this fixes the problem there, you may want to have it working in Python3 just pass it to the MySQLdb.connectas parameter

self.connection = MySQLdb.connect(
                    host=host, user=settings_DB.db_config['USER'],
                    port=port, passwd=settings_DB.db_config['PASSWORD'], 
                    db=settings_DB.db_config['NAME'],
                    local_infile=True)

Filtering Table rows using Jquery

tr:not(:contains(.... work for me

function busca(busca){
    $("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
    $("#listagem tr:contains('"+busca+"')").css("display", "");
}

How to get box-shadow on left & right sides only

In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1; on the surrounding DIVs.

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

Detect application heap size in Android

Here's how you do it:

Getting the max heap size that the app can use:

Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory();

Getting how much of the heap your app currently uses:

long usedMemory=runtime.totalMemory() - runtime.freeMemory();

Getting how much of the heap your app can now use (available memory) :

long availableMemory=maxMemory-usedMemory;

And, to format each of them nicely, you can use:

String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize); 

Matplotlib: "Unknown projection '3d'" error

First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.

Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")

I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.

If you're running version 0.99, try doing this instead of using using the projection keyword argument:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization! 
fig = plt.figure()

ax = Axes3D(fig) #<-- Note the difference from your original code...

X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()

This should work in matplotlib 1.0.x, as well, not just 0.99.

Regex matching beginning AND end strings

^dbo\..*_fn$

This should work you.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Link to reload current page

Completely idempotent url that preserves path, parameters, and anchor.

 <a href="javascript:"> click me </a>

it only uses a little tiny bit of JS.

EDIT: this does not reload the page. It is a link that does nothing.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Write applications in C or C++ for Android?

The official position seems to be that this isn't something you'd ever "want to do". See this thread on the Android Developers list. Google envisage android running on a variety of different devices (CPUs, displays, etc). The best way to enable development is therefore to use (portable) managed code that targets the Dalvik VM. For this reason, the Android SDK doesn't support C/C++.

BUT, take a look at this page:

Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.

The managed application framework appears to be layered on-top of these libraries. The page goes on to list the C/C++ libs: standard C library, media, 3D, SQL lite, and others.

So all you need is a compiler chain that will compile C/C++ to the appropriate CPU (ARM, in the case of the G1). Some brief instructions on how to do this are here.

What I don't know is where to find descriptions of the APIs that these libraries provide. I'd guess there may be header files buried in the SDK somewhere, but documentation may be sketchy/missing. But I think it can be done!

Hope thats useful. For the record, I haven't written any native android apps - just a few simple managed ones.

Andy

How to pass Multiple Parameters from ajax call to MVC Controller

You're making an HTTP POST, but trying to pass parameters with the GET query string syntax. In a POST, the data are passed as named parameters and do not use the param=value&foo=bar syntax. Using jQuery's ajax method lets you create a javascript object with the named parameters, like so:

$.ajax({
  url: '/Home/SaveChart',
  type: 'POST',
  async: false,
  dataType: 'text',
  processData: false,    
  data: { 
      input: JSON.stringify(IVRInstant.data), 
      name: $("#wrkname").val()
  },
  success: function (data) { }
});

"The page has expired due to inactivity" - Laravel 5.5

My case was solved with SESSION_DOMAIN, in my local machine had to be set to xxx.localhost. It was causing conflicts with the production SESSION_DOMAIN, xxx.com that was set directly in the session.php config file.

Loading local JSON file

If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON() method of JQuery ->

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

getJSON() is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)

RuntimeWarning: DateTimeField received a naive datetime

Quick and dirty - Turn it off:

USE_TZ = False

in your settings.py

IF Statement multiple conditions, same statement

You could also do this if you think it's more clear:

if (columnname != a 
  && columnname != b 
  && columnname != c
{
   if (checkbox.checked || columnname != A2)
   {
      "statement 1"
   }
}

Uninstall Node.JS using Linux command line?

If you have yum you could do:

yum remove nodesource-release* nodejs

yum clean all

And after that check if its deleted:

rpm -qa 'node|npm'

npm install won't install devDependencies

Check the NPM docs for install

With the --production flag (or when the NODE_ENV environment variable is set to production), npm will not install modules listed in devDependencies."

The --only={prod[uction]|dev[elopment]} argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV."

Have you tried

npm install --only=dev

If you are worried that your package.json might be incorrect, best thing to do is this. Create a new folder, and run:

npm init --yes

Then:

npm install --save-dev brunch@^2.0.4
npm install --save-dev cssnano-brunch@^1.1.5
npm install --save-dev javascript-brunch@^1.8.0
npm install --save-dev sass-brunch@^1.9.2
npm install --save-dev uglify-js-brunch@^1.7.8
npm install jquery@^2.1.4 --save

And you should be good to go! Otherwise, will keep posting other options.

Check your npm configuration:

npm config list

npm gets its config settings from the command line, environment variables, and npmrc files. So check environment variables, and the npmrc file.

Still failing?

Ok, create a new folder, ideally somewhere else on your filesystem. ie. not in same folder hierarchy. For instance, C:\myNewFolder - the closer to the base C: drive the better.

Then run:

npm init --yes

Now run:

npm install underscore --save

and finally:

npm install mocha --save-dev

Does everything work as expected?

What I am trying to do is understand whether your problem is global, or something local to the previous folder and dependencies.

Finding all cycles in a directed graph

Regarding your question about the Permutation Cycle, read more here: https://www.codechef.com/problems/PCYCLE

You can try this code (enter the size and the digits number):

# include<cstdio>
using namespace std;

int main()
{
    int n;
    scanf("%d",&n);

    int num[1000];
    int visited[1000]={0};
    int vindex[2000];
    for(int i=1;i<=n;i++)
        scanf("%d",&num[i]);

    int t_visited=0;
    int cycles=0;
    int start=0, index;

    while(t_visited < n)
    {
        for(int i=1;i<=n;i++)
        {
            if(visited[i]==0)
            {
                vindex[start]=i;
                visited[i]=1;
                t_visited++;
                index=start;
                break;
            }
        }
        while(true)
        {
            index++;
            vindex[index]=num[vindex[index-1]];

            if(vindex[index]==vindex[start])
                break;
            visited[vindex[index]]=1;
            t_visited++;
        }
        vindex[++index]=0;
        start=index+1;
        cycles++;
    }

    printf("%d\n",cycles,vindex[0]);

    for(int i=0;i<(n+2*cycles);i++)
    {
        if(vindex[i]==0)
            printf("\n");
        else
            printf("%d ",vindex[i]);
    }
}

Composer Update Laravel

The following works for me:

composer update --no-scripts

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Since I don't believe "Please use..." plus some random code that is unrelated to the question is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.

When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES

Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES
                          ('col1', 'col3', 'col2')

It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.

Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.

TLDR

using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x => 
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));

This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.

how to set active class to nav menu from twitter bootstrap

<div class="nav-collapse">
                <ul class="nav">
                    <li class="home"><a href="~/Home/Index">Home</a></li>
                    <li class="Project"><a href="#">Project</a></li>
                    <li class="Customer"><a href="#">Customer</a></li>
                    <li class="Staff"><a href="#">Staff</a></li>
                    <li class="Broker"><a href="~/Home/Broker">Broker</a></li>
                    <li class="Sale"><a href="#">Sale</a></li>
                </ul>
</div>

then for each page you add this:

//home

 $(document).ready(function () {
        $('.home').addClass('active');
    });

//Project page

$(document).ready(function () {
            $('.Project').addClass('active');
        });

//Customer page

 $(document).ready(function () {
                $('.Customer').addClass('active');
            });

//staff page

 $(document).ready(function () {
                $('.Staff').addClass('active');
            });

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Make content horizontally scroll inside a div

The problem is that your imgs will always bump down to the next line because of the containing div.

In order to get around this, you need to place the imgs in their own div with a width wide enough to hold all of them. Then you can use your styles as is.

So, when I set the imgs to 120px each and place them inside a

div#insideDiv{
    width:800px;
}

it all works.

Adjust width as necessary.

See http://jsfiddle.net/jasongennaro/8YfRe/

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

Force decimal point instead of comma in HTML5 number input (client-side)

one option is javascript parseFloat()... never do parse a "text chain" --> 12.3456 with point to a int... 123456 (int remove the point) parse a text chain to a FLOAT...

to send this coords to a server do this sending a text chain. HTTP only sends TEXT

in the client keep out of parsing the input coords with "int", work with text strings

if you print the cords in the html with php or similar... float to text and print in html

How to get current memory usage in android?

It depends on your definition of what memory query you wish to get.


Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.

For this, you can check the next values:

final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)

That's also what the DDMS tool of memory usage shows.


Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.


Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:

val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize

But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.

So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.


EDIT: seems Debug.getNativeHeapSize() changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.

If you want to get the real total and available native RAM , use this:

val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
        "free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
        "used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")

PHP checkbox set to check based on database value

Use checked="checked" attribute if you want your checkbox to be checked.

if condition in sql server update query

Since you're using SQL 2008:

UPDATE
    table_Name

SET
    column_A  
     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

    column_B  
     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
WHERE
    ID = @ID

If you were using SQL 2012:

UPDATE
    table_Name
SET
    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
    ID = @ID

How to import load a .sql or .csv file into SQLite?

Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

How to open up a form from another form in VB.NET?

You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type

dialogue1.show()

that's all !!!

How do you serve a file for download with AngularJS or Javascript?

In our current project at work we had a invisible iFrame and I had to feed the url for the file to the iFrame to get a download dialog box. On the button click, the controller generates the dynamic url and triggers a $scope event where a custom directive I wrote, is listing. The directive will append a iFrame to the body if it does not exist already and sets the url attribute on it.

EDIT: Adding a directive

appModule.directive('fileDownload', function ($compile) {
    var fd = {
        restrict: 'A',
        link: function (scope, iElement, iAttrs) {

            scope.$on("downloadFile", function (e, url) {
                var iFrame = iElement.find("iframe");
                if (!(iFrame && iFrame.length > 0)) {
                    iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
                    iElement.append(iFrame);
                }

                iFrame.attr("src", url);


            });
        }
    };

    return fd;
});

This directive responds to a controller event called downloadFile

so in your controller you do

$scope.$broadcast("downloadFile", url);

How to read from a file or STDIN in Bash?

Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen - this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV. None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec appropriately.

#!/bin/bash

(($#)) || set -- -
while (($#)); do
   { [[ $1 = - ]] || exec < "$1"; } &&
   while read -r; do
      printf '%s\n' "$REPLY"
   done
   shift
done

Filename's available in $1.

If no arguments are given, we artificially set - as the first positional parameter. We then loop on the parameters. If a parameter is not -, we redirect standard input from filename with exec. If this redirection succeeds we loop with a while loop. I'm using the standard REPLY variable, and in this case you don't need to reset IFS. If you want another name, you must reset IFS like so (unless, of course, you don't want that and know what you're doing):

while IFS= read -r line; do
    printf '%s\n' "$line"
done

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

Unable to start Service Intent

First, you do not need android:process=":remote", so please remove it, since all it will do is take up extra RAM for no benefit.

Second, since the <service> element contains an action string, use it:

public void onCreate(Bundle savedInstanceState) {    
      super.onCreate(savedInstanceState);  
      Intent intent=new Intent("com.sample.service.serviceClass");  
      this.startService(intent);
}

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

As others said, you simply put :not(.class). For CSS selectors, I recommend visiting this link, it's been very helpful throughout my journey: https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

div:not(.success) {
  color: red;
}

The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

*:not(p) {
  color: green;
}

What's the use of ob_start() in php?

This function isn't just for headers. You can do a lot of interesting stuff with this. Example: You could split your page into sections and use it like this:

$someTemplate->selectSection('header');
echo 'This is the header.';

$someTemplate->selectSection('content');
echo 'This is some content.';

You can capture the output that is generated here and add it at two totally different places in your layout.

how to convert object to string in java

I'm afraid your map contains something other than String objects. If you call toString() on a String object, you obtain the string itself.

What you get [Ljava.lang.String indicates you might have a String array.

"ssl module in Python is not available" when installing package with pip3

The python documentation is actually very clear, and following the instructions did the job whereas other answers I found here were not fixing this issue.

  1. first, install python 3.x.x from source using, for example with version 3.6.2 https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tar.xz

  2. make sure you have openssl installed by running brew install openssl

  3. unzip it and move to the python directory: tar xvzf Python-3.6.2.tar.xz && cd Python-3.6.2

  4. then if the python version is < 3.7, run

CPPFLAGS="-I$(brew --prefix openssl)/include" \ LDFLAGS="-L$(brew --prefix openssl)/lib" \ ./configure --with-pydebug 5. finallly, run make -s -j2 (-s is the silent flag, -j2 tells your machine to use 2 jobs)

How to bind to a PasswordBox in MVVM

Sorry, but you're doing it wrong.

People should have the following security guideline tattooed on the inside of their eyelids:
Never keep plain text passwords in memory.

The reason the WPF/Silverlight PasswordBox doesn't expose a DP for the Password property is security related.
If WPF/Silverlight were to keep a DP for Password it would require the framework to keep the password itself unencrypted in memory. Which is considered quite a troublesome security attack vector. The PasswordBox uses encrypted memory (of sorts) and the only way to access the password is through the CLR property.

I would suggest that when accessing the PasswordBox.Password CLR property you'd refrain from placing it in any variable or as a value for any property.
Keeping your password in plain text on the client machine RAM is a security no-no.
So get rid of that public string Password { get; set; } you've got up there.

When accessing PasswordBox.Password, just get it out and ship it to the server ASAP. Don't keep the value of the password around and don't treat it as you would any other client machine text. Don't keep clear text passwords in memory.

I know this breaks the MVVM pattern, but you shouldn't ever bind to PasswordBox.Password Attached DP, store your password in the ViewModel or any other similar shenanigans.

If you're looking for an over-architected solution, here's one:
1. Create the IHavePassword interface with one method that returns the password clear text.
2. Have your UserControl implement a IHavePassword interface.
3. Register the UserControl instance with your IoC as implementing the IHavePassword interface.
4. When a server request requiring your password is taking place, call your IoC for the IHavePassword implementation and only than get the much coveted password.

Just my take on it.

-- Justin

google-services.json for different productFlavors

According to Firebase docs you can also use string resources instead of google-services.json.

Because this provider is just reading resources with known names, another option is to add the string resources directly to your app instead of using the Google Services gradle plugin. You can do this by:

  • Removing the google-services plugin from your root build.gradle
  • Deleting the google-services.json from your project
  • Adding the string resources directly
  • Deleting apply plugin: 'com.google.gms.google-services' from your app build.gradle

Example strings.xml:

<string name="google_client_id">XXXXXXXXX.apps.googleusercontent.com</string>
<string name="default_web_client_id">XXXX-XXXXXX.apps.googleusercontent.com</string>
<string name="gcm_defaultSenderId">XXXXXX</string>
<string name="google_api_key">AIzaXXXXXX</string>
<string name="google_app_id">1:XXXXXX:android:XXXXX</string>
<string name="google_crash_reporting_api_key">AIzaXXXXXXX</string>
<string name="project_id">XXXXXXX</string>

How do you completely remove Ionic and Cordova installation from mac?

Command to remove Cordova and ionic

  • For Window system

    • npm uninstall -g ionic
    • npm uninstall -g cordova
  • For Mac system

    • sudo npm uninstall -g ionic
    • sudo npm uninstall -g cordova
  • For install cordova and ionic

    • npm install -g cordova
    • npm install -g ionic

Note:

  • If you want to install in MAC System use before npm use sudo only.
  • And plan to install specific version of ionic and cordova then use @(version no.).

eg.

sudo npm install -g [email protected]

sudo npm install -g [email protected]

How to access SOAP services from iPhone

I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.

I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.

Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc

How to create a data file for gnuplot?

For future reference, I had the same problem

"warning: Skipping unreadable file"

under Linux. The reason was that I love using Tab-completing and in gnuplot this added a whitespace at the end that I did not really notice

gnuplot> plot "./datafile.txt "

Emulate a 403 error page

I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:

  1. Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
  2. Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
  3. now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
  4. echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!

        <?php header('HTTP/1.0 403 Forbidden');
        $contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
        exit($contents);
    

Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

How to add a button dynamically using jquery

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}