Programs & Examples On #Mx record

Splitting a string at every n-th character

You could do it like this:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))

Resize to fit image in div, and center horizontally and vertically

NOT SUPPORTED BY IE

More info here: Can I Use?

_x000D_
_x000D_
.container {_x000D_
  overflow: hidden;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.

On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.

for more detailed check this below link

https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Integrated application pool mode

When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.

There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.

Classic application pool mode

When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.

This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.

Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?

Original source: Introduction to IIS Architecture

App can't be opened because it is from an unidentified developer

Terminal type:

Last login: Thu Dec 20 08:28:43 on console
 ~ ? sudo spctl --master-disable
Password:
 ~ ? spctl --status
assessments disabled
 ~ ?

System Preferences->Security & Privacy

enter image description here

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

Copy table without copying data

Try:

CREATE TABLE foo SELECT * FROM bar LIMIT 0

Or:

CREATE TABLE foo SELECT * FROM bar WHERE 1=0

Use of Application.DoEvents()

Check out the MSDN Documentation for the Application.DoEvents method.

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

Extension exists but uuid_generate_v4 fails

if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB

psql -d -c "create EXTENSION pgcrypto;"

How to display alt text for an image in chrome

You can put title attribute to tag.I hope it will work.

<img src="smiley.gif" title="Smiley face" width="42" height="42">

Why should you use strncpy instead of strcpy?

That depends on our requirement. For windows users

We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.

These links will help you more to know about strcpy and strncpy and where we can use.

about strcpy

about strncpy

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Can a java file have more than one class?

In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.

The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.

ExecuteNonQuery doesn't return results

if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement.

How to Set Count On

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Adding script tag to React/JSX

You can also use react helmet

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.com/example" />
                <script src="/path/to/resource.js" type="text/javascript" />
            </Helmet>
            ...
        </div>
    );
  }
};

Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly.

How to copy selected lines to clipboard in vim

First check if your vim installation has clipboard support.

vim --version

If clipboard support is installed you will see:

+clipboard
+X11
+xterm_clipboard

If clipboard support is not installed you will see:

-clipboard
-X11
-xterm_clipboard

To install clipboard support:

apt-get install vim-gnome

Once you have verified that clipboard support is installed do the following:

  1. Position your cursor to the first line you want to copy.
  2. Press Shiftv to enter visual mode.
  3. Press ? to select multiple lines
  4. Press "+y to copy the selected text to system clipboard.
  5. Now you can copy the selected text to browser, text editor etc.
  6. Press "+p if you want to copy system clipboard text to vim.

Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :

  1. Open .vimrc file and add following text at the end of file:

     nnoremap <C-c> "+y
     vnoremap <C-c> "+y
     nnoremap <C-p> "+p
     vnoremap <C-p> "+p
    
  2. Save and reload your .vimrc to apply the new changes.

  3. Position your cursor to the first line you want to copy.

  4. Press Shiftv to enter visual mode.

  5. Press ? to select multiple lines

  6. Press Ctrlc to copy the selected text to system clipboard.

  7. Now you can copy the selected text to browser, text editor etc.

  8. Press Ctrlp if you want to copy system clipboard text to vim.

Note: This is for ubuntu systems.

Default behavior of "git push" without a branch specified

Here is a very handy and helpful information about Git Push: Git Push: Just the Tip

The most common use of git push is to push your local changes to your public upstream repository. Assuming that the upstream is a remote named "origin" (the default remote name if your repository is a clone) and the branch to be updated to/from is named "master" (the default branch name), this is done with: git push origin master

git push origin will push changes from all local branches to matching branches the origin remote.

git push origin master will push changes from the local master branch to the remote master branch.

git push origin master:staging will push changes from the local master branch to the remote staging branch if it exists.

How do I delete an item or object from an array using ng-click?

I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.

So, for instance, on your HTML...

<a class="btn" ng-remove-birthday="$index">Delete</a>

Then, create a directive...

angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
    return function(scope, element, attrs){
        angular.element(element.bind('click', function(){
            myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);  
        };       
    };
}])

Then in your service...

angular.module('myApp').factory('myService', [function(){
    return {
        removeBirthday: function(birthdayIndex, scope){
            scope.bdays.splice(birthdayIndex);
            scope.$apply();
        }
    };
}]);

When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.

For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.

Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)

Happy Developing!!!

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

Replacement for deprecated sizeWithFont: in iOS 7?

// max size constraint
CGSize maximumLabelSize = CGSizeMake(184, FLT_MAX)

// font
UIFont *font = [UIFont fontWithName:TRADE_GOTHIC_REGULAR size:20.0f];

// set paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

// dictionary of attributes
NSDictionary *attributes = @{NSFontAttributeName:font,
                             NSParagraphStyleAttributeName: paragraphStyle.copy};

CGRect textRect = [string boundingRectWithSize: maximumLabelSize
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil];

CGSize expectedLabelSize = CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));

Jquery each - Stop loop and return object

Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find call's return value:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

_x000D_
_x000D_
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';

var test = findXX('o322');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

Determine which MySQL configuration file is being used

I installed mysql use brew install mysql

mysqld --verbose --help | less

And it shows:

enter image description here

How to run a script at a certain time on Linux?

Look at the following:

echo "ls -l" | at 07:00

This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:

http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html

Hope it helps!

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

How to make cross domain request

If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

How do I escape the wildcard/asterisk character in bash?

I'll add a bit to this old thread.

Usually you would use

$ echo "$FOO"

However, I've had problems even with this syntax. Consider the following script.

#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"

The * needs to be passed verbatim to curl, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*. You also can't quote $curl_opts because it will be recognized as a single (invalid) option to curl.

curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

Therefore I would recommend the use of the bash variable $GLOBIGNORE to prevent filename expansion altogether if applied to the global pattern, or use the set -f built-in flag.

#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"  ## no filename expansion

Applying to your original example:

me$ FOO="BAR * BAR"

me$ echo $FOO
BAR file1 file2 file3 file4 BAR

me$ set -f
me$ echo $FOO
BAR * BAR

me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR

CSS: background image on background color

really interesting problem, haven't seen it yet. this code works fine for me. tested it in chrome and IE9

<html>
<head>
<style>
body{
    background-image: url('img.jpg');
    background-color: #6DB3F2;
}
</style>
</head>
<body>
</body>
</html>

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

How do I scroll the UIScrollView when the keyboard appears?

All the answers here seem to forget about landscape possibilities. If you would like this to work when the device is rotated to a landscape view, then you will face problems.

The trick here is that although the view is aware of the orientation, the keyboard is not. This means in Landscape, the keyboards width is actually its height and visa versa.

To modify Apples recommended way of changing the content insets and get it support landscape orientation, I would recommend using the following:

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(keyboardWillBeHidden:)
             name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight ) {
        CGSize origKeySize = keyboardSize;
        keyboardSize.height = origKeySize.width;
        keyboardSize.width = origKeySize.height;
    }
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
    scroller.contentInset = contentInsets;
    scroller.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect rect = scroller.frame;
    rect.size.height -= keyboardSize.height;
    NSLog(@"Rect Size Height: %f", rect.size.height);

    if (!CGRectContainsPoint(rect, activeField.frame.origin)) {
        CGPoint point = CGPointMake(0, activeField.frame.origin.y - keyboardSize.height);
        NSLog(@"Point Height: %f", point.y);
        [scroller setContentOffset:point animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent    
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

The part to pay attention to here is the following:

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight ) {
    CGSize origKeySize = keyboardSize;
    keyboardSize.height = origKeySize.width;
    keyboardSize.width = origKeySize.height;
}

What is does, is detects what orientation the device is in. If it is landscape, it will 'swap' the width and height values of the keyboardSize variable to ensure that the correct values are being used in each orientation.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:

$(form).on('change change.dp dp.change changeDate' function () {...})

And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:

// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {  
    $('input[bs-datepicker]').on('focus', function (e){
        e.currentTarget.focusValue = e.currentTarget.value;
    });        
    $('input[bs-datepicker]').on('blur', function (e){
        if (e.currentTarget.focusValue !== e.currentTarget.value) {
            var event = new Event('change', { bubbles: true });
            e.currentTarget.dispatchEvent(event);
        }
    });
})

This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.

Hope this helps someone!

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

psycopg2: insert multiple rows with one query

Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:

engine = create_engine(
    "postgresql+psycopg2://scott:tiger@host/dbname",
    use_batch_mode=True)

http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109

Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..

How to specify an element after which to wrap in css flexbox?

Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,

flex-grow: 1;
min-width: 33%; 

If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.

Make sure to have parent element with,

flex-wrap: wrap

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

As per String literals:

String literals can be enclosed within single quotes (i.e. '...') or double quotes (i.e. "..."). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).

The backslash character (i.e. \) is used to escape characters which otherwise will have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter r or R. Such strings are called raw strings and use different rules for backslash escape sequences.

In triple-quoted strings, unescaped newlines and quotes are allowed, except that the three unescaped quotes in a row terminate the string.

Unless an r or R prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.

So ideally you need to replace the line:

data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

To any one of the following characters:

  • Using raw prefix and single quotes (i.e. '...'):

      data = open(r'C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener')
    
  • Using double quotes (i.e. "...") and escaping backslash character (i.e. \):

      data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
    
  • Using double quotes (i.e. "...") and forwardslash character (i.e. /):

      data = open("C:/Users/miche/Documents/school/jaar2/MIK/2.6/vektis_agb_zorgverlener")
    

How to place two divs next to each other?

Try to use flexbox model. It is easy and short to write.

Live Jsfiddle

CSS:

#wrapper {
  display: flex;
  border: 1px solid black;
}
#first {
    border: 1px solid red;
}
#second {
    border: 1px solid green;
}

default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions

How to make circular background using css?

If you want to do it with only 1 element, you can use the ::before and ::after pseudo elements for the same div instead of a wrapper.
See http://css-tricks.com/pseudo-element-roundup/

What is the difference between java and core java?

"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.

Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

First create table without auto_increment,

CREATE TABLE `members`(
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL
    PRIMARY KEY (memberid) 
) ENGINE = MYISAM;

after set id as index,

ALTER TABLE `members` ADD INDEX(`id`);

after set id as auto_increment,

ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;

Or

CREATE TABLE IF NOT EXISTS `members` (
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL,
      PRIMARY KEY (`memberid`),
      KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Return value in SQL Server stored procedure

I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.

just create additional User_Seq table: with two fields: id Uniq index and SeqVal nvarchar(1)

and create next SP, and generated ID value from this SP and put to new User row!

CREATE procedure [dbo].[User_NextValue]
as
begin
    set NOCOUNT ON


    declare @existingId int = (select isnull(max(UserId)+1, 0)  from dbo.User)

    insert into User_Seq (SeqVal) values ('a')
    declare @NewSeqValue int = scope_identity()     

    if @existingId > @NewSeqValue 
    begin  

        set identity_insert User_Seq  on
        insert into User_Seq (SeqID) values (@existingId)     
        set @NewSeqValue = scope_identity()     
    end

    delete from User_Seq WITH (READPAST)

return @NewSeqValue

end

How do you cache an image in Javascript

I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.

as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

The name 'model' does not exist in current context in MVC3

Update: 5/5/2015 For your MVC 5 project you need to set the Version to 5.0.0.0 in your /views/web.config

<system.web.webPages.razor>
     <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</system.web.webPages.razor>

Parsing huge logfiles in Node.js - read in line-by-line

I have made a node module to read large file asynchronously text or JSON. Tested on large files.

var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');

module.exports = FileReader;

function FileReader(){

}

FileReader.prototype.read = function(pathToFile, callback){
    var returnTxt = '';
    var s = fs.createReadStream(pathToFile)
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        //console.log('reading line: '+line);
        returnTxt += line;        

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(){
        console.log('Error while reading file.');
    })
    .on('end', function(){
        console.log('Read entire file.');
        callback(returnTxt);
    })
);
};

FileReader.prototype.readJSON = function(pathToFile, callback){
    try{
        this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
    }
    catch(err){
        throw new Error('json file is not valid! '+err.stack);
    }
};

Just save the file as file-reader.js, and use it like this:

var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});

How to exit from ForEach-Object in PowerShell

To stop the pipeline of which ForEach-Object is part just use the statement continue inside the script block under ForEach-Object. continue behaves differently when you use it in foreach(...) {...} and in ForEach-Object {...} and this is why it's possible. If you want to carry on producing objects in the pipeline discarding some of the original objects, then the best way to do it is to filter out using Where-Object.

Difference between Role and GrantedAuthority in Spring Security

Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

Capturing multiple line output into a Bash variable

Parsing multiple output

Introduction

So your myscript output 3 lines, could look like:

myscript() { echo $'abc\ndef\nghi'; }

or

myscript() { local i; for i in abc def ghi ;do echo $i; done ;}

Ok this is a function, not a script (no need of path ./), but output is same

myscript
abc
def
ghi

Considering result code

To check for result code, test function will become:

myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}

1. Storing multiple output in one single variable, showing newlines

Your operation is correct:

RESULT=$(myscript)

About result code, you could add:

RCODE=$?

even in same line:

RESULT=$(myscript) RCODE=$?

Then

echo $RESULT 
abc def ghi

echo "$RESULT"
abc
def
ghi

echo ${RESULT@Q}
$'abc\ndef\nghi'

printf "%q\n" "$RESULT"
$'abc\ndef\nghi'

but for showing variable definition, use declare -p:

declare -p RESULT
declare -- RESULT="abc
def
ghi"

2. Parsing multiple output in array, using mapfile

Storing answer into myvar variable:

mapfile -t myvar < <(myscript)
echo ${myvar[2]}
ghi

Showing $myvar:

declare -p myvar
declare -a myvar=([0]="abc" [1]="def" [2]="ghi")

Considering result code

In case you have to check for result code, you could:

RESULT=$(myscript) RCODE=$?
mapfile -t myvar <<<"$RESULT"

3. Parsing multiple output by consecutives read in command group

{ read firstline; read secondline; read thirdline;} < <(myscript)
echo $secondline
def

Showing variables:

declare -p firstline secondline thirdline
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"

I often use:

{ read foo;read foo total use free foo ;} < <(df -k /)

Then

declare -p use free total
declare -- use="843476"
declare -- free="582128"
declare -- total="1515376"

Considering result code

Same prepended step:

RESULT=$(myscript) RCODE=$?
{ read firstline; read secondline; read thirdline;} <<<"$RESULT"

declare -p firstline secondline thirdline RCODE
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
declare -- RCODE="50"

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

Are there bookmarks in Visual Studio Code?

You need to do this via an extension as of the version 1.8.1.

  1. Go to View ? Extensions. This will open Extensions Panel.

  2. Type bookmark to list all related extensions.

  3. Install


I personally like "Numbered Bookmarks" - it is pretty simple and powerful.

Go to the line you need to create a bookmark.

Click Ctrl + Shift + [some number]

Ex: Ctrl + Shift + 2

Now you can jump to this line from anywhere by pressing Ctrl + number

Ex: Ctrl + 2

How to query between two dates using Laravel and Eloquent?

If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

How to parse a string to an int in C++?

You can use Boost's lexical_cast, which wraps this in a more generic interface. lexical_cast<Target>(Source) throws bad_lexical_cast on failure.

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
    public int s_id;
    public String s_name, c_name, dob;
}
class Program
{
    static void Main(string[] args)
    {
        student[] arr = new student[4];

        for(int i = 0; i < 4; i++)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");


            arr[i].s_id = Int32.Parse(Console.ReadLine());
            arr[i].s_name = Console.ReadLine();
            arr[i].c_name = Console.ReadLine();
            arr[i].s_dob = Console.ReadLine();
       }
    }
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

Global variables in Javascript across multiple files

If you're using node:

  1. Create file to declare value, say it's called values.js:
export let someValues = {
  value1: 0
}

Then just import it as needed at the top of each file it's used in (e.g., file.js):

import { someValues } from './values'

console.log(someValues);

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

C# List<> Sort by x then y

Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:

 public void SortList() {
     MyList.Sort(delegate(MyClass a, MyClass b)
     {
         int xdiff = a.x.CompareTo(b.x);
         if (xdiff != 0) return xdiff;
         else return a.y.CompareTo(b.y);
     });
 }

Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.

Good PHP ORM Library?

I have had great experiences with Idiorm and Paris. Idiorm is a small, simple ORM library. Paris is an equally simple Active Record implementation built on Idiorm. It's for PHP 5.2+ with PDO. It's perfect if you want something simple that you can just drop into an existing application.

How do you use script variables in psql?

You need to use one of the procedural languages such as PL/pgSQL not the SQL proc language. In PL/pgSQL you can use vars right in SQL statements. For single quotes you can use the quote literal function.

How to upload and parse a CSV file in php

You can try with this:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

How to use Bootstrap in an Angular project?

Provided you use the Angular-CLI to generate new projects, there's another way to make bootstrap accessible in Angular 2/4.

  1. Via command line interface navigate to the project folder. Then use npm to install bootstrap:
    $ npm install --save bootstrap. The --save option will make bootstrap appear in the dependencies.
  2. Edit the .angular-cli.json file, which configures your project. It's inside the project directory. Add a reference to the "styles" array. The reference has to be the relative path to the bootstrap file downloaded with npm. In my case it's: "../node_modules/bootstrap/dist/css/bootstrap.min.css",

My example .angular-cli.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "bootstrap-test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Now bootstrap should be part of your default settings.

Creating a new ArrayList in Java

Material please go through this Link And also try this

 ArrayList<Class> myArray= new ArrayList<Class>();

replacing NA's with 0's in R dataframe

What Tyler Rinker says is correct:

AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0

will do just this.

What you are originally doing is that you are taking from airquality all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

I also got same error, compiling with -D flag fixed it, Try this:

g++ -Dstd=c++11

Android Studio suddenly cannot resolve symbols

In my multi-module project, the problem was that version of "com.android.support:appcompat-v7" in module A was "22.0.0", but in B - "22.2.0".

Solution: make sure
1. version of common libraries is same among modules.
2. each of modules compiles without any errors (try to build each of them from CLI).

Android lollipop change navigation bar color

You can change it directly in styles.xml file \app\src\main\res\values\styles.xml

This work on older versions, I was changing it in KitKat and come here.

What are allowed characters in cookies?

If you are using the variables later, you'll find that stuff like path actually will let accented characters through, but it won't actually match the browser path. For that you need to URIEncode them. So i.e. like this:

  const encodedPath = encodeURI(myPath);
  document.cookie = `use_pwa=true; domain=${location.host}; path=${encodedPath};`

So the "allowed" chars, might be more than what's in the spec. But you should stay within the spec, and use URI-encoded strings to be safe.

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

Proper way to empty a C-String

Two other ways are strcpy(str, ""); and string[0] = 0

To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

#include <string.h>

...

int i=0;
for(i=0;i<strlen(string);i++)
{
    string[i] = 0;
}

In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

I hope this was useful for anybody ;)

Javascript - Get Image height

It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Ignore case in Python strings

I can't find any other built-in way of doing case-insensitive comparison: The python cook-book recipe uses lower().

However you have to be careful when using lower for comparisons because of the Turkish I problem. Unfortunately Python's handling for Turkish Is is not good. i is converted to I, but I is not converted to i. I is converted to i, but i is not converted to I.

How to list files and folder in a dir (PHP)

If you have problems with accessing to the path, maybe you need to put this:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/"; 

// Open the folder
 $dir_handle = @opendir($root . $path) or die("Unable to open $path");

Adding external library into Qt Creator project

The proper way to do this is like this:

LIBS += -L/path/to -lpsapi

This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.

In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_ variable, e.g.:

LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi

Text in Border CSS HTML

_x000D_
_x000D_
<fieldset>_x000D_
  <legend> YOUR TITLE </legend>_x000D_
  _x000D_
  _x000D_
  <p>_x000D_
  Lorem ipsum dolor sit amet, est et illum reformidans, at lorem propriae mei. Qui legere commodo mediocritatem no. Diam consetetur._x000D_
  </p>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

Open window in JavaScript with HTML inserted

You can open a new popup window by following code:

var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using

newFile.html

And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

<script>    
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>

And add whatever you want to add in your body tag. using following code

<script>    
 var myWindow = window.open("newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;
    } 

myWindow.window.close();
 </script>

it is as simple as that.

JPA EntityManager: Why use persist() over merge()?

You may have come here for advice on when to use persist and when to use merge. I think that it depends the situation: how likely is it that you need to create a new record and how hard is it to retrieve persisted data.

Let's presume you can use a natural key/identifier.

  • Data needs to be persisted, but once in a while a record exists and an update is called for. In this case you could try a persist and if it throws an EntityExistsException, you look it up and combine the data:

    try { entityManager.persist(entity) }

    catch(EntityExistsException exception) { /* retrieve and merge */ }

  • Persisted data needs to be updated, but once in a while there is no record for the data yet. In this case you look it up, and do a persist if the entity is missing:

    entity = entityManager.find(key);

    if (entity == null) { entityManager.persist(entity); }

    else { /* merge */ }

If you don't have natural key/identifier, you'll have a harder time to figure out whether the entity exist or not, or how to look it up.

The merges can be dealt with in two ways, too:

  1. If the changes are usually small, apply them to the managed entity.
  2. If changes are common, copy the ID from the persisted entity, as well as unaltered data. Then call EntityManager::merge() to replace the old content.

How to upload a file in Django?

I faced the similar problem, and solved by django admin site.

# models
class Document(models.Model):
    docfile = models.FileField(upload_to='documents/Temp/%Y/%m/%d')

    def doc_name(self):
        return self.docfile.name.split('/')[-1] # only the name, not full path

# admin
from myapp.models import Document
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('doc_name',)
admin.site.register(Document, DocumentAdmin)

Java; String replace (using regular expressions)?

Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.

https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)

In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.

Flutter : Vertically center column

Solution as proposed by Aziz would be:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children:children,
)

It would not be in the exact center because of padding:

padding: new EdgeInsets.all(25.0),

To make exactly center Column - at least in this case - you would need to remove padding.

How to use export with Python on Linux

I have an excellent answer.

#! /bin/bash

output=$(git diff origin/master..origin/develop | \
python -c '
  # DO YOUR HACKING
  variable1_to_be_exported="Yo Yo"
  variable2_to_be_exported="Honey Singh"
  … so on
  magic=""
  magic+="export onShell-var1=\""+str(variable1_to_be_exported)+"\"\n"
  magic+="export onShell-var2=\""+str(variable2_to_be_exported)+"\""  
  print magic
'
)

eval "$output"
echo "$onShell-var1" // Output will be Yo Yo
echo "$onShell-var2" // Output will be Honey Singh

Mr Alex Tingle is correct about those processes and sub-process stuffs

How it can be achieved is like the above I have mentioned. Key Concept is :

  1. Whatever printed from python will be stored in the variable in the catching variable in bash [output]
  2. We can execute any command in the form of string using eval
  3. So, prepare your print output from python in a meaningful bash commands
  4. use eval to execute it in bash

And you can see your results

NOTE Always execute the eval using double quotes or else bash will mess up your \ns and outputs will be strange

PS: I don't like bash but your have to use it

What is the use of join() in Python threading?

When making join(t) function for both non-daemon thread and daemon thread, the main thread (or main process) should wait t seconds, then can go further to work on its own process. During the t seconds waiting time, both of the children threads should do what they can do, such as printing out some text. After the t seconds, if non-daemon thread still didn't finish its job, and it still can finish it after the main process finishes its job, but for daemon thread, it just missed its opportunity window. However, it will eventually die after the python program exits. Please correct me if there is something wrong.

What's the equivalent of Java's Thread.sleep() in JavaScript?

Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.

How to use BeanUtils.copyProperties?

As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance

 private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
                @Nullable String... ignoreProperties) throws BeansException {

            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");

            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                            "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }
            **PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null &&
                                ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                            catch (Throwable ex) {
                                throw new FatalBeanException(
                                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        }

So it's better to use plain setters given the cost reflection

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

how do I create an array in jquery?

You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.

array('Item 1', 'Item 2', 'Items 3')  // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2')  // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')

Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:

['Item 1', 'Item 2', 'Item 3']  // array (numerically indexed)

An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:

{ first : 'Item 1', second : 'Item 2' }  // object (a.k.a. "associative array")

They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.


* Technically everything is an Object in Javascript, please put that aside for this argument. ;)

How to get root directory in yii2

Open file D:\wamp\www\yiistore2\common\config\params-local.php

Paste below code before return

Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));

After inserting above code in params-local.php file your file should look like this.

Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));

return [
];

Now to get path of your root (in my case its D:\wamp\www\yiistore2) directory you can use below code in any php file.

echo Yii::getAlias('@anyname');

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Disable Tensorflow debugging information

for tensorflow 2.1.0, following code works fine.

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

php random x digit number

function random_number($size = 5)
{
    $random_number='';
    $count=0;
    while ($count < $size ) 
        {
            $random_digit = mt_rand(0, 9);
            $random_number .= $random_digit;
            $count++;
        }
    return $random_number;  
}

How to delete projects in Intellij IDEA 14?

Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like

'C:/xxxxxx/pom.xml' already exists in VFS

Here is what I found would work.

  1. Remove module
  2. File -> Invalidate Cache (at this point the Intelli IDEA wants to restart)
  3. Close project
  4. Delete the folder form system explorer.
  5. Now you can create a project with same name as before.

Can I use if (pointer) instead of if (pointer != NULL)?

The relevant use cases for null pointers are

  • Redirection to something like a deeper tree node, which may not exist or has not been linked yet. That's something you should always keep closely encapsulated in a dedicated class, so readability or conciseness isn't that much of an issue here.
  • Dynamic casts. Casting a base-class pointer to a particular derived-class one (something you should again try to avoid, but may at times find necessary) always succeeds, but results in a null pointer if the derived class doesn't match. One way to check this is

    Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr);
    if(derived_ptr != nullptr) { ... }
    

    (or, preferrably, auto derived_ptr = ...). Now, this is bad, because it leaves the (possibly invalid, i.e. null) derived pointer outside of the safety-guarding if block's scope. This isn't necessary, as C++ allows you to introduce boolean-convertable variables inside an if-condition:

    if(auto derived_ptr = dynamic_cast<Derived*>(base_ptr)) { ... }
    

    which is not only shorter and scope-safe, it's also much more clear in its intend: when you check for null in a separate if-condition, the reader wonders "ok, so derived_ptr must not be null here... well, why would it be null?" Whereas the one-line version says very plainly "if you can safely cast base_ptr to Derived*, then use it for...".

    The same works just as well for any other possible-failure operation that returns a pointer, though IMO you should generally avoid this: it's better to use something like boost::optional as the "container" for results of possibly failing operations, rather than pointers.

So, if the main use case for null pointers should always be written in a variation of the implicit-cast-style, I'd say it's good for consistency reasons to always use this style, i.e. I'd advocate for if(ptr) over if(ptr!=nullptr).


I'm afraid I have to end with an advert: the if(auto bla = ...) syntax is actually just a slightly cumbersome approximation to the real solution to such problems: pattern matching. Why would you first force some action (like casting a pointer) and then consider that there might be a failure... I mean, it's ridiculous, isn't it? It's like, you have some foodstuff and want to make soup. You hand it to your assistant with the task to extract the juice, if it happens to be a soft vegetable. You don't first look it at it. When you have a potato, you still give it to your assistant but they slap it back in your face with a failure note. Ah, imperative programming!

Much better: consider right away all the cases you might encounter. Then act accordingly. Haskell:

makeSoupOf :: Foodstuff -> Liquid
makeSoupOf p@(Potato{..}) = mash (boil p) <> water
makeSoupOf vegetable
 | isSoft vegetable  = squeeze vegetable <> salt
makeSoupOf stuff  = boil (throwIn (water<>salt) stuff)

Haskell also has special tools for when there is really a serious possibility of failure (as well as for a whole bunch of other stuff): monads. But this isn't the place for explaining those.

⟨/advert⟩

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

Split large string in n-size chunks in JavaScript

This is a fast and straightforward solution -

_x000D_
_x000D_
function chunkString (str, len) {_x000D_
  const size = Math.ceil(str.length/len)_x000D_
  const r = Array(size)_x000D_
  let offset = 0_x000D_
  _x000D_
  for (let i = 0; i < size; i++) {_x000D_
    r[i] = str.substr(offset, len)_x000D_
    offset += len_x000D_
  }_x000D_
  _x000D_
  return r_x000D_
}_x000D_
_x000D_
console.log(chunkString("helloworld", 3))_x000D_
// => [ "hel", "low", "orl", "d" ]_x000D_
_x000D_
// 10,000 char string_x000D_
const bigString = "helloworld".repeat(1000)_x000D_
console.time("perf")_x000D_
const result = chunkString(bigString, 3)_x000D_
console.timeEnd("perf")_x000D_
console.log(result)_x000D_
// => perf: 0.385 ms_x000D_
// => [ "hel", "low", "orl", "dhe", "llo", "wor", ... ]
_x000D_
_x000D_
_x000D_

How to customize the configuration file of the official PostgreSQL Docker image?

When you run the official entrypoint (A.K.A. when you launch the container), it runs initdb in $PGDATA (/var/lib/postgresql/data by default), and then it stores in that directory these 2 files:

  • postgresql.conf with default manual settings.
  • postgresql.auto.conf with settings overriden automatically with ALTER SYSTEM commands.

The entrypoint also executes any /docker-entrypoint-initdb.d/*.{sh,sql} files.

All this means you can supply a shell/SQL script in that folder that configures the server for the next boot (which will be immediately after the DB initialization, or the next times you boot the container).

Example:

conf.sql file:

ALTER SYSTEM SET max_connections = 6;
ALTER SYSTEM RESET shared_buffers;

Dockerfile file:

FROM posgres:9.6-alpine
COPY *.sql /docker-entrypoint-initdb.d/
RUN chmod a+r /docker-entrypoint-initdb.d/*

And then you will have to execute conf.sql manually in already-existing databases. Since configuration is stored in the volume, it will survive rebuilds.


Another alternative is to pass -c flag as many times as you wish:

docker container run -d postgres -c max_connections=6 -c log_lock_waits=on

This way you don't need to build a new image, and you don't need to care about already-existing or not databases; all will be affected.

How to get the full URL of a Drupal page?

Maybe what you want is just plain old predefined variables.

Consider trying

$_SERVER['REQUEST_URI'']

Or read more here.

How to add image that is on my computer to a site in css or html?

The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:

<img src="C:\users\home\pictures\picture.png"/>

I want to show all tables that have specified column name

If you're trying to query an Oracle database, you might want to use

select owner, table_name 
from all_tab_columns
where column_name = 'ColName';

Angular: How to update queryParams without changing route

If you want to change query params without change the route. see below example might help you: current route is : /search & Target route is(without reload page) : /search?query=love

    submit(value: string) {
      this.router.navigate( ['.'],  { queryParams: { query: value } })
        .then(_ => this.search(q));
    }
    search(keyword:any) { 
    //do some activity using }

please note : you can use this.router.navigate( ['search'] instead of this.router.navigate( ['.']

TCPDF output without saving file

Print the PDF header (using header() function) like: header("Content-type: application/pdf");

and then just echo the content of the PDF file you created (instead of writing it to disk).

Java properties UTF-8 encoding in Eclipse

Answer for "pre-Java-9" is below. As of Java 9, properties files are saved and loaded in UTF-8 by default, but falling back to ISO-8859-1 if an invalid UTF-8 byte sequence is detected. See the Java 9 release notes for details.


Properties files are ISO-8859-1 by definition - see the docs for the Properties class.

Spring has a replacement which can load with a specified encoding, using PropertiesFactoryBean.

EDIT: As Laurence noted in the comments, Java 1.6 introduced overloads for load and store which take a Reader/Writer. This means you can create a reader for the file with whatever encoding you want, and pass it to load. Unfortunately FileReader still doesn't let you specify the encoding in the constructor (aargh) so you'll be stuck with chaining FileInputStream and InputStreamReader together. However, it'll work.

For example, to read a file using UTF-8:

Properties properties = new Properties();
InputStream inputStream = new FileInputStream("path/to/file");
try {
    Reader reader = new InputStreamReader(inputStream, "UTF-8");
    try {
        properties.load(reader);
    } finally {
        reader.close();
    }
} finally {
   inputStream.close();
}

JAXB: how to marshall map into <key>value</key>

There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.

The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.

In the default case for a Map<String, String>, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string key and one xs:string value. That's a pretty clear interface contract.

What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.

To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.

public enum KeyType {
 KEY, KEY2;
}

@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;

That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.

On the other hand, if you wish to simplify the default generated structure

<map>
    <entry>
        <key>KEY</key>
        <value>VALUE</value>
    </entry>
    <entry>
        <key>KEY2</key>
        <value>VALUE2</value>
    </entry>
</map>

To something simpler like this

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>

You can use a MapAdapter that converts the Map to an array of MapElements as follows:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;

    private MapElements() {
    } //Required by JAXB

    public MapElements(String key, String value) {
        this.key = key;
        this.value = value;
    }
}


public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    public MapAdapter() {
    }

    public MapElements[] marshal(Map<String, String> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, String> r = new TreeMap<String, String>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

Fixing a systemd service 203/EXEC failure (no such file or directory)

If that is a copy/paste from your script, you've permuted this line:

#!/usr/env/bin bash

There's no #!/usr/env/bin, you meant #!/usr/bin/env.

What is the canonical way to check for errors using the CUDA runtime API?

Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess) 
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

You can then wrap each API call with the gpuErrchk macro, which will process the return status of the API call it wraps, for example:

gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );

If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr and the application will exit. You could conceivably modify gpuAssert to raise an exception rather than call exit() in a more sophisticated application if it were required.

A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:

kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );

will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:

kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );

in which case the cudaMemcpy call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.

Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:

#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) assert(0);
   }
}

How do I parse a string into a number with Dart?

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

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

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

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

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

Hope this helps!

Input group - two inputs close to each other

If you want to include a "Title" field within it that can be selected with the <select> HTML element, that too is possible

PREVIEW enter image description here

CODE SNIPPET

<div class="form-group">
  <div class="input-group input-group-lg">
    <div class="input-group-addon">
      <select>
        <option>Mr.</option>
        <option>Mrs.</option>
        <option>Dr</option>
      </select>
    </div>
    <div class="input-group-addon">
      <span class="fa fa-user"></span>
    </div>
    <input type="text" class="form-control" placeholder="Name...">
  </div>
</div>

How can I use threading in Python?

With borrowing from this post we know about choosing between the multithreading, multiprocessing, and async/asyncio and their usage.

Python 3 has a new built-in library in order to make concurrency and parallelism: concurrent.futures

So I'll demonstrate through an experiment to run four tasks (i.e. .sleep() method) by Threading-Pool:

from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep, time

def concurrent(max_worker):
    futures = []
    tic = time()
    with ThreadPoolExecutor(max_workers=max_worker) as executor:
        futures.append(executor.submit(sleep, 2))  # Two seconds sleep
        futures.append(executor.submit(sleep, 1))
        futures.append(executor.submit(sleep, 7))
        futures.append(executor.submit(sleep, 3))
        for future in as_completed(futures):
            if future.result() is not None:
                print(future.result())
    print(f'Total elapsed time by {max_worker} workers:', time()-tic)

concurrent(5)
concurrent(4)
concurrent(3)
concurrent(2)
concurrent(1)

Output:

Total elapsed time by 5 workers: 7.007831811904907
Total elapsed time by 4 workers: 7.007944107055664
Total elapsed time by 3 workers: 7.003149509429932
Total elapsed time by 2 workers: 8.004627466201782
Total elapsed time by 1 workers: 13.013478994369507

[NOTE]:

  • As you can see in the above results, the best case was 3 workers for those four tasks.
  • If you have a process task instead of I/O bound or blocking (multiprocessing instead of threading) you can change the ThreadPoolExecutor to ProcessPoolExecutor.

Count unique values using pandas groupby

This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:

df.groupby(['group']).agg(['min','max','count','nunique'])

Hope you find it useful

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

Change the "MSBuild project build output verbosity" to "Detailed" or above. To do this, follow these steps:

  1. Bring up the Options dialog (Tools -> Options...).
  2. In the left-hand tree, select the Projects and Solutions node, and then select Build and Run.
    • Note: if this node doesn't show up, make sure that the checkbox at the bottom of the dialog Show all settings is checked.
  3. In the tools/options page that appears, set the MSBuild project build output verbosity level to the appropriate setting depending on your version:

  4. Build the project and look in the output window.

Check out the MSBuild messages. The ResolveAssemblyReferences task, which is the task from which MSB3247 originates, should help you debug this particular issue.

My specific case was an incorrect reference to SqlServerCe. See below. I had two projects referencing two different versions of SqlServerCe. I went to the project with the older version, removed the reference, then added the correct reference.

Target ResolveAssemblyReferences:
    Consider app.config remapping of assembly "System.Data.SqlServerCe, ..." 
        from Version "3.5.1.0" [H:\...\Debug\System.Data.SqlServerCe.dll] 
        to Version "9.0.242.0" [C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PublicAssemblies\System.Data.SqlServerCe.dll]
        to solve conflict and get rid of warning.
    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets : 
        warning MSB3247: Found conflicts between different versions of the same dependent assembly.

You do not have to open each assembly to determine the versions of referenced assemblies.

  • You can check the Properties of each Reference.
  • Open the project properties and check the versions of the References section.
  • Open the projects with a Text Editor.
  • Use .Net Reflector.

How to "crop" a rectangular image into a square with CSS?

I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

setTimeout or setInterval?

If you set the interval in setInterval too short, it may fire before the previous call to the function has been completed. I ran into this problem with a recent browser (Firefox 78). It resulted in the garbage collection not being able to free memory fast enough and built up a huge memory leak. Using setTimeout(function, 500); gave the garbage collection enough time to clean up and keep the memory stable over time.

Serg Hospodarets mentioned the problem in his answer and I fully agree with his remarks, but he didn't include the memory leak/garbage collection-problem. I experienced some freezing, too, but the memory usage ran up to 4 GB in no time for some minuscule task, which was the real bummer for me. Thus, I think this answer is still beneficial to others in my situation. I would have put it in a comment, but lack the reputation to do so. I hope you don't mind.

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

How to fast-forward a branch to head?

In your situation, git rebase would also do the trick. Since you have no changes that master doesn't have, git will just fast-forward. If you are working with a rebase workflow, that might be more advisable, as you wouldn't end up with a merge commit if you mess up.

username@workstation:~/work$ git status
# On branch master
# Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
#   (use "git pull" to update your local branch)
#
nothing to commit, working directory clean
username@workstation:~/work$ git rebase
First, rewinding head to replay your work on top of it...
Fast-forwarded master to refs/remotes/origin/master.
# On branch master
nothing to commit, working directory clean

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

What is the use of the square brackets [] in sql statements?

Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....

Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.

How to format a string as a telephone number in C#

If you can get i["MyPhone"] as a long, you can use the long.ToString() method to format it:

Convert.ToLong(i["MyPhone"]).ToString("###-###-####");

See the MSDN page on Numeric Format Strings.

Be careful to use long rather than int: int could overflow.

How to determine the version of the C++ standard used by the compiler?

From the Bjarne Stroustrup C++0x FAQ:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.

These are the C++ standards and what value you should be able to expect in __cplusplus:

  • C++ pre-C++98: __cplusplus is 1.
  • C++98: __cplusplus is 199711L.
  • C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
  • C++11: __cplusplus is 201103L.
  • C++14: __cplusplus is 201402L.
  • C++17: __cplusplus is 201703L.

If the compiler might be an older gcc, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.

The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).

Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).

How to convert a Binary String to a base 10 integer in Java

You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);

Serialize an object to XML

my work code. Returns utf8 xml enable empty namespace.

// override StringWriter
public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

private string GenerateXmlResponse(Object obj)
{    
    Type t = obj.GetType();

    var xml = "";

    using (StringWriter sww = new Utf8StringWriter())
    {
        using (XmlWriter writer = XmlWriter.Create(sww))
        {
            var ns = new XmlSerializerNamespaces();
            // add empty namespace
            ns.Add("", "");
            XmlSerializer xsSubmit = new XmlSerializer(t);
            xsSubmit.Serialize(writer, obj, ns);
            xml = sww.ToString(); // Your XML
        }
    }
    return xml;
}

Example returns response Yandex api payment Aviso url:

<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank


¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

Salt and hash a password in Python

Here's my proposition:

for i in range(len(rserver.keys())):
    salt = uuid.uuid4().hex
    print(salt)
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
    rsalt.set(rserver.keys()[i], salt)

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

Script not served by static file handler on IIS7.5

I had the same problem. When I added Static content feaute for IIS, It works fine.

Save plot to image file instead of displaying it using Matplotlib

If, like me, you use Spyder IDE, you have to disable the interactive mode with :

plt.ioff()

(this command is automatically launched with the scientific startup)

If you want to enable it again, use :

plt.ion()

Changing project port number in Visual Studio 2013

Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.

enter image description here

On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file

C:\Users\<username>\Documents\IISExpress\config\applicationhost.config

I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.

After installing with pip, "jupyter: command not found"

Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:

First verify this is a PATH issue:

Check if the path returned by which jupyter is covered by the sudo user:

sudo env | grep ^PATH

(As opposed to the current user: env | grep ^PATH)

If its not covered - add a soft link from it to one of the covered paths. For ex:

sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin

Now you sould be able to run:

sudo jupyter notebook

Reporting Services Remove Time from DateTime in Expression

Found the solution from here

This gets the last second of the previous day:

DateAdd("s",-1,DateAdd("d",1,Today())

This returns the last second of the previous week:

=dateadd("d", -Weekday(Now), (DateAdd("s",-1,DateAdd("d",1,Today()))))

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

How to get the device's IMEI/ESN programmatically in android?

As in API 26 getDeviceId() is depreciated so you can use following code to cater API 26 and earlier versions

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei="";
if (android.os.Build.VERSION.SDK_INT >= 26) {
  imei=telephonyManager.getImei();
}
else
{
  imei=telephonyManager.getDeviceId();
}

Don't forget to add permission requests for READ_PHONE_STATE to use the above code.

UPDATE: From Android 10 its is restricted for user apps to get non-resettable hardware identifiers like IMEI.

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

Finding element in XDocument?

My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

In short, you can create a GetElement function:

private XElement GetElement(XDocument doc,string elementName)
{
    foreach (XNode node in doc.DescendantNodes())
    {
        if (node is XElement)
        {
            XElement element = (XElement)node;
            if (element.Name.LocalName.Equals(elementName))
                return element;
        }
    }
    return null;
}

Which you can then call like this:

XElement element = GetElement(doc,"Band");

Note that this will return null if no matching element is found.

C# getting its own class name

I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.

typeof(MyProgram).Name

Sending an HTTP POST request on iOS

Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs

This method fills html forms inside Google Forms. Hope it helps someone using Swift.

var url = NSURL(string: urlstring)

var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)

How to get character array from a string?

You can also use Array.from.

_x000D_
_x000D_
var m = "Hello world!";
console.log(Array.from(m))
_x000D_
_x000D_
_x000D_

This method has been introduced in ES6.

Reference

Array.from

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];
}

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

How do I convert a String object into a Hash object?

works in rails 4.1 and support symbols without quotes {:a => 'b'}

just add this to initializers folder:

class String
  def to_hash_object
    JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
  end
end

Java Ordered Map

I have used Simple Hash map, linked list and Collections to sort a Map by values.

import java.util.*;
import java.util.Map.*;
public class Solution {

    public static void main(String[] args) {
        // create a simple hash map and insert some key-value pairs into it
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("Python", 3);
        map.put("C", 0);
        map.put("JavaScript", 4);
        map.put("C++", 1);
        map.put("Golang", 5);
        map.put("Java", 2);
        // Create a linked list from the above map entries
        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
        // sort the linked list using Collections.sort()
        Collections.sort(list, new Comparator<Entry<String, Integer>>(){
        @Override
         public int compare(Entry<String, Integer> m1, Entry<String, Integer> m2) {
        return m1.getValue().compareTo(m2.getValue());
        }
      });
      for(Entry<String, Integer> value: list) {
         System.out.println(value);
     }
   }
}

The output is:

C=0
C++=1
Java=2
Python=3
JavaScript=4
Golang=5

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

We can mute it in this way (device and simulator need different values):

Add the Name OS_ACTIVITY_MODE and the Value ${DEBUG_ACTIVITY_MODE} and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).

enter image description here

Add User-Defined Setting DEBUG_ACTIVITY_MODE, then add Any iOS Simulator SDK for Debug and set it's value to disable (in Project -> Build settings -> + -> User-Defined Setting)

enter image description here

How to JUnit test that two List<E> contain the same elements in the same order?

For excellent code-readability, Fest Assertions has nice support for asserting lists

So in this case, something like:

Assertions.assertThat(returnedComponents).containsExactly("One", "Two", "Three");

Or make the expected list to an array, but I prefer the above approach because it's more clear.

Assertions.assertThat(returnedComponents).containsExactly(argumentComponents.toArray());

TNS Protocol adapter error while starting Oracle SQL*Plus

Another possibility (esp. with multiple Oracle homes)

set ORACLE_SID=$SID

sqlplus /nolog

conn / as sysdba;

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

List all files and directories in a directory + subdirectories

string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);

where *.* is pattern to match files

If the Directory is also needed you can go like this:

 foreach (var file in allfiles){
     FileInfo info = new FileInfo(file);
 // Do something with the Folder or just add them to a list via nameoflist.add();
 }

What is a None value?

None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.


For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.

Read this info from a great blog: http://python-history.blogspot.in/

Dropping a connected user from an Oracle 10g database schema

Just my two cents : the best way (but probably not the quickest in the short term) would probably be for each developer to work on his own database instance (see rule #1 for database work).

Installing Oracle on a developer station has become a no brainer since Oracle Database 10g Express Edition.

How can I get the content of CKEditor using JQuery?


i add ckEditor by adding DLL in toolBox.
html code:

<CKEditor:CKEditorControl ID="editor1" runat="server" 
            BasePath="ckeditor" ContentsCss="ckeditor/contents.css" 
            Height="250px" 
            TemplatesFiles="ckeditor/themes/default/theme.js" FilebrowserBrowseUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserFlashBrowseUrl="ckeditor/plugins/FileManager/index.html" FilebrowserFlashUploadUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserImageBrowseLinkUrl="ckeditor/plugins/FileManager/index.html" FilebrowserImageBrowseUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserImageUploadUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserUploadUrl="ckeditor/plugins/FileManager/index.html" BackColor="#FF0066" 
                    DialogButtonsOrder="Rtl" 
                    FontNames="B Yekan;B Yekan,tahoma;Arial/Arial, Helvetica, sans-serif; Comic Sans MS/Comic Sans MS, cursive; Courier New/Courier New, Courier, monospace; Georgia/Georgia, serif; Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif; Tahoma/Tahoma, Geneva, sans-serif; Times New Roman/Times New Roman, Times, serif; Trebuchet MS/Trebuchet MS, Helvetica, sans-serif; Verdana/Verdana, Geneva, sans-serif" 
                    ResizeDir="Vertical" ResizeMinHeight="350" UIColor="#CACACA">dhd fdh</CKEditor:CKEditorControl>

for get data of it.
jquery:

var editor  = $('textarea iframe html body').html();
    alert(editor); 

What is the difference between React Native and React?

  1. React-Native is a framework for developing Android & iOS applications which shares 80% - 90% of Javascript code.

While React.js is a parent Javascript library for developing web applications.

  1. While you use tags like <View>, <Text> very frequently in React-Native, React.js uses web html tags like <div> <h1> <h2>, which are only synonyms in dictionary of web/mobile developments.

  2. For React.js you need DOM for path rendering of html tags, while for mobile application: React-Native uses AppRegistry to register your app.

I hope this is an easy explanation for quick differences/similarities in React.js and React-Native.

How to iterate through two lists in parallel?

Python 3

for f, b in zip(foo, bar):
    print(f, b)

zip stops when the shorter of foo or bar stops.

In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.

Python 2

In Python 2, zip returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by itertools.izip or itertools.izip_longest, which returns an iterator instead of a list.

import itertools
for f,b in itertools.izip(foo,bar):
    print(f,b)
for f,b in itertools.izip_longest(foo,bar):
    print(f,b)

izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.


Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                              ['red', 'blue', 'green']):
    print('{} {} {}'.format(num, color, cheese))

prints

1 red manchego
2 blue stilton
3 green brie

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

Checking if a collection is empty in Java: which is the best method?

if (CollectionUtils.isNotEmpty(listName))

Is the same as:

if(listName != null && !listName.isEmpty())

In first approach listName can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0 is something unnecessary at all, also i learned that it is slower than using .isEmpty()

Difference in days between two dates in Java?

If you're looking for a solution that returns proper number or days between e.g. 11/30/2014 23:59 and 12/01/2014 00:01 here's solution using Joda Time.

private int getDayDifference(long past, long current) {
    DateTime currentDate = new DateTime(current);
    DateTime pastDate = new DateTime(past);
    return currentDate.getDayOfYear() - pastDate.getDayOfYear();
} 

This implementation will return 1 as a difference in days. Most of the solutions posted here calculate difference in milliseconds between two dates. It means that 0 would be returned because there's only 2 minutes difference between these two dates.

Is there a job scheduler library for node.js?

Both node-schedule and node-cron we can use to implement cron-based schedullers.

NOTE : for generating cron expressions , you can use this cron_maker

What version of MongoDB is installed on Ubuntu

inside shell:

mongod --version

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

! [rejected] master -> master (fetch first)

Its Simple use this command:

git push -f origin master

and it will get your work done

Why is pydot unable to find GraphViz's executables in Windows 8?

The problem is that the path to GraphViz was not found by the pydot module as shown in the traceback:

'GraphViz\'s executables not found'

I solved this problem on my windows 7 machine by adding the GraphViz bin directory to my computer's PATH. Then restarting my python IDE to use the updated path.

  1. Install GraphViz if you haven't already (I used the MSI download)
  2. Get the path for gvedit.exe (for me it was "C:\Program Files (x86)\Graphviz2.34\bin\")
  3. Add this path to the computer's PATH
  4. One way to get to environment settings to set your path is to click on each of these button/menu options: start->computer->system properties->advanced settings->environment variables
  5. Click Edit User path
  6. Add this string to the end of your Variable value list (including semicolon): ;C:\Program Files (x86)\Graphviz2.34\bin
  7. Click OK
  8. Restart your Python IDE

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

Hive ParseException - cannot recognize input near 'end' 'string'

The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end).

The solution: use backticks around the offending column name:

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

With the added backticks around end, the query works as expected.

Reserved words in Amazon Hive (as of February 2013):

IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS

Source: This Hive ticket from the Facebook Phabricator tracker

How to Compare two Arrays are Equal using Javascript?

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

How to group by week in MySQL?

The accepted answer above did not work for me, because it ordered the weeks by alphabetical order, not chronological order:

2012/1
2012/10
2012/11
...
2012/19
2012/2

Here's my solution to count and group by week:

SELECT CONCAT(YEAR(date), '/', WEEK(date)) AS week_name, 
       YEAR(date), WEEK(date), COUNT(*)
FROM column_name
GROUP BY week_name
ORDER BY YEAR(DATE) ASC, WEEK(date) ASC

Generates:

YEAR/WEEK   YEAR   WEEK   COUNT
2011/51     2011    51      15
2011/52     2011    52      14
2012/1      2012    1       20
2012/2      2012    2       14
2012/3      2012    3       19
2012/4      2012    4       19

Sort a List of objects by multiple fields

If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply. Imagine you have a program dealing with cities:



    protected Set<City> cities;
    (...)
    Field temperatureField = City.class.getDeclaredField("temperature");
    Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
    Field rainfallField = City.class.getDeclaredField("rainfall");
    program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
    (...)
    public void showCitiesSortBy(Field... fields) {
        List<City> sortedCities = new ArrayList<City>(cities);
        Collections.sort(sortedCities, new City.CityMultiComparator(fields));
        for (City city : sortedCities) {
            System.out.println(city.toString());
        }
    }

where you can replace hard-coded field names by field names deduced from a user request in your program.

In this example, City.CityMultiComparator<City> is a static nested class of class City implementing Comparator:



    public static class CityMultiComparator implements Comparator<City> {
        protected List<Field> fields;

        public CityMultiComparator(Field... orderedFields) {
            fields = new ArrayList<Field>();
            for (Field field : orderedFields) {
                fields.add(field);
            }
        }

        @Override
        public int compare(City cityA, City cityB) {
            Integer score = 0;
            Boolean continueComparison = true;
            Iterator itFields = fields.iterator();

            while (itFields.hasNext() && continueComparison) {
                Field field = itFields.next();
                Integer currentScore = 0;
                if (field.getName().equalsIgnoreCase("temperature")) {
                    currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
                } else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
                    currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
                } else if (field.getName().equalsIgnoreCase("rainfall")) {
                    currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
                }
                if (currentScore != 0) {
                    continueComparison = false;
                }
                score = currentScore;
            }

            return score;
        }
    }


You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field objects by objects of a class you could call SortedField, containing a Field object, plus another field meaning ascendant or descendant.

How to sort rows of HTML table that are called from MySQL

It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.

In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)

Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.

You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.

Moment.js - two dates difference in number of days

the diff method returns the difference in milliseconds. Instantiating moment(diff) isn't meaningful.

You can define a variable :

var dayInMilliseconds = 1000 * 60 * 60 * 24;

and then use it like so :

diff / dayInMilliseconds // --> 15

Edit

actually, this is built into the diff method, dubes' answer is better

Exploring Docker container's file system

Here are a couple different methods...

A) Use docker exec (easiest)

Docker version 1.3 or newer supports the command exec that behave similar to nsenter. This command can run new process in already running container (container must have PID 1 process running already). You can run /bin/bash to explore container state:

docker exec -t -i mycontainer /bin/bash

see Docker command line documentation

B) Use Snapshotting

You can evaluate container filesystem this way:

# find ID of your running container:
docker ps

# create image (snapshot) from container filesystem
docker commit 12345678904b5 mysnapshot

# explore this filesystem using bash (for example)
docker run -t -i mysnapshot /bin/bash

This way, you can evaluate filesystem of the running container in the precise time moment. Container is still running, no future changes are included.

You can later delete snapshot using (filesystem of the running container is not affected!):

docker rmi mysnapshot

C) Use ssh

If you need continuous access, you can install sshd to your container and run the sshd daemon:

 docker run -d -p 22 mysnapshot /usr/sbin/sshd -D
 
 # you need to find out which port to connect:
 docker ps

This way, you can run your app using ssh (connect and execute what you want).

D) Use nsenter

Use nsenter, see Why you don't need to run SSHd in your Docker containers

The short version is: with nsenter, you can get a shell into an existing container, even if that container doesn’t run SSH or any kind of special-purpose daemon

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

Use URI builder in Android or create URL with variables

Using appendEncodePath() could save you multiple lines than appendPath(), the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());

Warning: Failed propType: Invalid prop `component` supplied to `Route`

There is an stable release on the react-router-dom (v5) with the fix for this issue.

link to github issue

A variable modified inside a while loop is not remembered

How about a very simple method

    +call your while loop in a function 
     - set your value inside (nonsense, but shows the example)
     - return your value inside 
    +capture your value outside
    +set outside
    +display outside


    #!/bin/bash
    # set -e
    # set -u
    # No idea why you need this, not using here

    foo=0
    bar="hello"

    if [[ "$bar" == "hello" ]]
    then
        foo=1
        echo "Setting  \$foo to $foo"
    fi

    echo "Variable \$foo after if statement: $foo"

    lines="first line\nsecond line\nthird line"

    function my_while_loop
    {

    echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2; return 2;
        echo "Variable \$foo updated to $foo inside if inside while loop"
        fi

        echo -e $lines | while read line
do
    if [[ "$line" == "second line" ]]
    then
    foo=2;          
    echo "Variable \$foo updated to $foo inside if inside while loop"
    return 2;
    fi

    # Code below won't be executed since we returned from function in 'if' statement
    # We aready reported the $foo var beint set to 2 anyway
    echo "Value of \$foo in while loop body: $foo"

done
}

    my_while_loop; foo="$?"

    echo "Variable \$foo after while loop: $foo"


    Output:
    Setting  $foo 1
    Variable $foo after if statement: 1
    Value of $foo in while loop body: 1
    Variable $foo after while loop: 2

    bash --version

    GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
    Copyright (C) 2007 Free Software Foundation, Inc.

How to print GETDATE() in SQL Server with milliseconds in time?

these 2 are the same:

Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

enter image description here

Running PHP script from the command line

On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

Encrypt and decrypt a password in Java

I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Use the date function:

select date(timestamp_field) from table

From a character field representation to a date you can use:

select date(substring('2011/05/26 09:00:00' from 1 for 10));

Test code:

create table test_table (timestamp_field timestamp);
insert into test_table (timestamp_field) values(current_timestamp);
select timestamp_field, date(timestamp_field) from test_table;

Test result:

pgAdmin result

pgAdmin result wide

Can we add div inside table above every <tr>?

"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page

For example:

<table>
    <tbody class="green">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
    <tbody class="blue">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
</table>

secondly, you can put "div" tag inside "td" tag.

<table>
    <tr>
        <td>
            <div></div>
        </td>
    </tr>
</table>

Further questions are always welcome.

Converting bool to text in C++

Use boolalpha to print bool to string.

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

How many parameters are too many?

If you start having to mentally count off the parameters in the signature and match them to the call, then it is time to refactor!

How to convert a table to a data frame

While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable)). Using the example from @X.X:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> data.frame(rbind(freq_t))
  X3 X4 X5
4  1  8  2
6  2  4  1
8 12  0  2

If the column names do not start with numbers, the X won't get added to the front of them.

Find the 2nd largest element in an array with minimum number of comparisons

case 1-->9 8 7 6 5 4 3 2 1
case 2--> 50 10 8 25 ........
case 3--> 50 50 10 8 25.........
case 4--> 50 50 10 8 50 25.......

public void second element()  
{
      int a[10],i,max1,max2;  
      max1=a[0],max2=a[1];  
      for(i=1;i<a.length();i++)  
      {  
         if(a[i]>max1)  
          {
             max2=max1;  
             max1=a[i];  
          }  
         else if(a[i]>max2 &&a[i]!=max1)  
           max2=a[i];  
         else if(max1==max2)  
           max2=a[i];  
      }  
}

Loading scripts after page load?

The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)

To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:

var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);

Waiting until two async blocks are executed before starting another block

Not to say other answers are not great for certain circumstances, but this is one snippet I always user from Google:

- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {


    if (signInDoneSel) {
        [self performSelector:signInDoneSel];
    }

}

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Bootstrap tab activation with JQuery

Add an id attribute to a html tag

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Then using JQuery

$("#tab_aaa").tab('show');

JS how to cache a variable

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

Jquery

Set a value to the session storage.

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

How to implement onBackPressed() in Fragments?

Here is my solution for that issue:

in Activity A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE)
    {
        if(resultCode == Activity.RESULT_OK)
        {
            tvTitle.setText(data.getExtras().getString("title", ""));
        }
    }
}

in Activity B:

@Override
public void onBackPressed() 
{
    setResult(Activity.RESULT_OK, getIntent());

    super.onBackPressed();
}

activity b holds the fragment.

in fragment:

private void setText(String text)
    {
        Intent intent = new Intent();
        intent.putExtra("title", text);
        getActivity().setIntent(intent);
    }

in that way the Intent Object "data" in activity A will get the string from the fragment