Programs & Examples On #Puttycyg

How to use graphics.h in codeblocks?

AFAIK, in the epic DOS era there is a header file named graphics.h shipped with Borland Turbo C++ suite. If it is true, then you are out of luck because we're now in Windows era.

Common elements comparison between 2 lists

1) Method1 saving list1 is dictionary and then iterating each elem in list2

def findarrayhash(a,b):
    h1={k:1 for k in a}
    for val in b:
        if val in h1:
            print("common found",val)
            del h1[val]
        else:
            print("different found",val)
    for key in h1.iterkeys():
        print ("different found",key)

Finding Common and Different elements:

2) Method2 using set

def findarrayset(a,b):
    common = set(a)&set(b)
    diff=set(a)^set(b)
    print list(common)
    print list(diff) 

jQuery ui datepicker with Angularjs

myModule.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'dd/mm/yy',
                onSelect: function (date) {   
                    var ar=date.split("/");
                    date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
                    ngModelCtrl.$setViewValue(date.getTime());
                //    scope.course.launchDate = date;
                    scope.$apply();
                }
            });

        }
    };
});

HTML Code :

<input type="text" jqdatepicker  ng-model="course.launchDate" required readonly />

Append text to file from command line without using io redirection

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

JavaScript: How to find out if the user browser is Chrome?

Check this: How to detect Safari, Chrome, IE, Firefox and Opera browser?

In your case:

var isChrome = (window.chrome.webstore || window.chrome.runtime) && !!window.chrome;

How to highlight cell if value duplicate in same column for google spreadsheet?

While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:

    =COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1

Please note that in this example I will be using the range A1:C50. The first parameter ($A$1:$C$50) should be replaced with the range on which you would like to highlight duplicates!


to highlight duplicates:

  1. Select the whole range on which the duplicate marking is wanted.
  2. On the menu: Format > Conditional formatting...
  3. Under Apply to range, select the range to which the rule should be applied.
  4. In Format cells if, select Custom formula is on the dropdown.
  5. In the textbox insert the given formula, adjusting the range to match step (3).

Why does it work?

COUNTIF(range, criterion), will compare every cell in range to the criterion, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $ signs) so that we always view the full range.

The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4)), will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.

ROW() and COLUMN() will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3 will return 3 for ROW(), and 2 for COLUMN()).

Then we use: ADDRESS(row, column, [absolute_relative_mode]) to translate the numeric row and column to a cell reference (like B3. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4 returns the formatting INDIRECT() likes.

INDIRECT(), will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF() will test every cell in the range against ours, and return the count.

The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1. The > 1 is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.


Sources:

Angular and debounce

This is the best solution I have found till now. Updates the ngModelon blur and debounce

import { Directive, Input, Output, EventEmitter,ElementRef } from '@angular/core';
import { NgControl, NgModel } from '@angular/forms';
import 'rxjs/add/operator/debounceTime'; 
import 'rxjs/add/operator/distinctUntilChanged';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';

@Directive({
    selector: '[ngModel][debounce]',
})
export class DebounceDirective {
    @Output()
    public onDebounce = new EventEmitter<any>();

    @Input('debounce')
    public debounceTime: number = 500;

    private isFirstChange: boolean = true;

    constructor(private elementRef: ElementRef, private model: NgModel) {
    }

    ngOnInit() {
        const eventStream = Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
            .map(() => {
                return this.model.value;
            })
            .debounceTime(this.debounceTime);

        this.model.viewToModelUpdate = () => {};

        eventStream.subscribe(input => {
            this.model.viewModel = input;
            this.model.update.emit(input);
        });
    }
}

as borrowed from https://stackoverflow.com/a/47823960/3955513

Then in HTML:

<input [(ngModel)]="hero.name" 
        [debounce]="3000" 
        (blur)="hero.name = $event.target.value"
        (ngModelChange)="onChange()"
        placeholder="name">

On blur the model is explicitly updated using plain javascript.

Example here: https://stackblitz.com/edit/ng2-debounce-working

Capture HTML Canvas as gif/jpg/png/pdf?

if you want to emebed the canvas you can use this snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id=canvas width=200 height=200></canvas>
    <iframe id='img' width=200 height=200></iframe>
    <script>
        window.onload = function() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.fillStyle = "green";
            context.fillRect(50, 50, 100, 100);
            document.getElementById('img').src = canvas.toDataURL("image/jpeg");
            console.log(canvas.toDataURL("image/jpeg"));
        }
    </script>
</body>
</html>

Disable asp.net button after click to prevent double clicking

This solution works if you are using asp.net validators:

<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
    Page_ClientValidate(group);
    if (Page_IsValid)
    {
        sender.disabled = "disabled";
        __doPostBack(sender.name, '');
    }
}</script>

and change the button:

<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />

OSError: [WinError 193] %1 is not a valid Win32 application

The error is pretty clear. The file hello.py is not an executable file. You need to specify the executable:

subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])

You'll need python.exe to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

According to the following article: https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/

If you have an INDEX on your where clause (if id is indexed in your case), then it is better not to use SQL_CALC_FOUND_ROWS and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using SQL_CALC_FOUND_ROWS is more efficient.

Overflow:hidden dots at the end

Hide text on load and show on hover

_x000D_
_x000D_
.hide-text {
  width: 70px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

span:hover {
   white-space: unset;
   text-overflow: unset;
}
_x000D_
<span class="hide-text"> How to hide text by dots and show text on hover</span>
_x000D_
_x000D_
_x000D_

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

Webpack how to build production code and how to use it

After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.

To build the production code the first thing you have to create is production configuration with optimization packages like,

  new webpack.optimize.CommonsChunkPlugin('common.js'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

Then in the package.json file you can configure the build procedure with this production configuration

"scripts": {
    "build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},

now you have to run the following command to initiate the build

npm run build

As per my production build configuration webpack will build the source to ./dist directory.

Now your UI code will be available in ./dist/ directory. Configure your server to serve these files as static assets. Done!

Format output string, right alignment

I really enjoy a new literal string interpolation in Python 3.6+:

line_new = f'{word[0]:>12}  {word[1]:>12}  {word[2]:>12}'

Reference: PEP 498 -- Literal String Interpolation

MSBUILD : error MSB1008: Only one project can be specified

For future readers.

I got this error because my specified LOG file had a space in it:

BEFORE:

/l:FileLogger,Microsoft.Build.Engine;logfile=c:\Folder With Spaces\My_Log.log

AFTER: (which resolved it)

/l:FileLogger,Microsoft.Build.Engine;logfile="c:\Folder With Spaces\My_Log.log"

Java ArrayList copy

List.copyOf ? unmodifiable list

You asked:

Is there no other way to assign a copy of a list

Java 9 brought the List.of methods for using literals to create an unmodifiable List of unknown concrete class.

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
List< LocalDate > dates = List.of( 
    today.minusDays( 1 ) ,  // Yesterday
    today ,                 // Today
    today.plusDays( 1 )     // Tomorrow
);

Along with that we also got List.copyOf. This method too returns an unmodifiable List of unknown concrete class.

List< String > colors = new ArrayList<>( 4 ) ;          // Creates a modifiable `List`. 
colors.add ( "AliceBlue" ) ;
colors.add ( "PapayaWhip" ) ;
colors.add ( "Chartreuse" ) ;
colors.add ( "DarkSlateGray" ) ;
List< String > masterColors = List.copyOf( colors ) ;   // Creates an unmodifiable `List`.

By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.

colors.remove( 2 ) ;          // SUCCEEDS. 
masterColors.remove( 2 ) ;    // FAIL - ERROR.

See this code run live at IdeOne.com.

dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]

colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]

masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]

You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.

So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.

enter image description here

The first list colors is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse (index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String such as OliveDrab or CornflowerBlue.

In contrast, the four elements of masterColors are fixed. No removing, no adding, and no substituting another color. That List implementation is unmodifiable.

How to increment variable under DOS?

None of these seemed to work for me:

@ECHO OFF

REM 1. Initialize our counter
SET /A "c=0"

REM Iterate through a dummy list. 
REM Notice how the counter is used: "CALL ECHO %%c%%" 
FOR /L %%i in (10,1,20) DO (

  REM 2. Increment counter
  SET /A "c+=1"

  REM 3. Print our counter "%c%" and some dummy data "%%i"
  CALL ECHO Line %%c%%: - Data: %%i
)

The answer was extracted from: https://www.tutorialspoint.com/batch_script/batch_script_arrays.htm (Section: Length of an Array)

Result:

Line 1: - Data: 10
Line 2: - Data: 11
Line 3: - Data: 12
Line 4: - Data: 13
Line 5: - Data: 14
Line 6: - Data: 15
Line 7: - Data: 16
Line 8: - Data: 17
Line 9: - Data: 18
Line 10: - Data: 19
Line 11: - Data: 20

How to get param from url in angular 4?

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}

how to set JAVA_OPTS for Tomcat in Windows?

It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:

You can set the minimum and maximum memory heap size with the

JVM -Xms and -Xmx parameters.

The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use

JAVA_OPTS=-Xms128m -Xmx1024m        

You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter

    -XX:MaxPermSize=256m

For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.

The following is an example of a setenv.bat file:

set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

We can also try this solution

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");

in this the spring automatically finds the class in the class path itself

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

[ :Unexpected operator in shell programming

In fact the "[" square opening bracket is just an internal shell alias for the test command.

So you can say:

test -f "/bin/bash" && echo "This system has a bash shell"

or

[ -f "/bin/bash" ] && echo "This system has a bash shell"

... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

Best practices to test protected methods with PHPUnit

You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class

class Example {
    protected function getMessage() {
        return 'hello';
    }
}

you create a subclass in ExampleTest.php:

class ExampleExposed extends Example {
    public function __call($method, array $args = array()) {
        if (!method_exists($this, $method))
            throw new BadMethodCallException("method '$method' does not exist");
        return call_user_func_array(array($this, $method), $args);
    }
}

Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.

Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.

class ExampleTest extends PHPUnit_Framework_TestCase {
    function testGetMessage() {
        $fixture = new ExampleExposed();
        self::assertEquals('hello', $fixture->getMessage());
    }
}

I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

What's the best practice for primary keys in tables?

There´s no problem in making your primary key from various fields, that's a Natural Key.

You can use a Identity column (associated with a unique index on the candidate fields) to make a Surrogate Key.

That´s an old discussion. I prefer surrogate keys in most situations.

But there´s no excuse for the lack of a key.

RE: EDIT

Yeah, there´s a lot of controversy about that :D

I don´t see any obvious advantage on natural keys, besides the fact that they are the natural choice. You will always think in Name, SocialNumber - or something like that - instead of idPerson.

Surrogate keys are the answer to some of the problems that natural keys have (propagating changes for example).

As you get used to surrogates, it seems more clean, and manageable.

But in the end, you´ll find out that it's just a matter of taste - or mindset -. People "think better" with natural keys, and others don´t.

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

Adding gif image in an ImageView in android

Showing GIF In Android

Create CustomGifView.java which extends View Class

 public class CustomGifView extends View {

 private InputStream gifInputStream;
 private Movie gifMovie;
 private int movieWidth, movieHeight;
 private long movieDuration;
 private long mMovieStart;

 public CustomGifView(Context context) {
  super(context);
  init(context);
 }

 public CustomGifView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init(context);
 }

 public CustomGifView(Context context, AttributeSet attrs, 
   int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  init(context);
 }

 private void init(Context context){
  setFocusable(true);
  gifInputStream = context.getResources()
    .openRawResource(R.drawable.YOUR_IMAGE);

  gifMovie = Movie.decodeStream(gifInputStream);
  movieWidth = gifMovie.width();
  movieHeight = gifMovie.height();
  movieDuration = gifMovie.duration();
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, 
   int heightMeasureSpec) {
  setMeasuredDimension(movieWidth, movieHeight);
 }

 public int getMovieWidth(){
  return movieWidth;
 }

 public int getMovieHeight(){
  return movieHeight;
 }

 public long getMovieDuration(){
  return movieDuration;
 }

 @Override
 protected void onDraw(Canvas canvas) {

  long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) {   // first time
            mMovieStart = now;
        }

        if (gifMovie != null) {

            int dur = gifMovie.duration();
            if (dur == 0) {
                dur = 1000;
            }

            int relTime = (int)((now - mMovieStart) % dur);

            gifMovie.setTime(relTime);

            gifMovie.draw(canvas, 0, 0);
            invalidate();

        }

 }

 }

Now call this class in your XML

 <Your_PackageName.CustomGifView
        android:id="@+id/gifview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

N.P

Modify AndroidManifest.xml to turn OFF hardwareAccelerated.

 android:hardwareAccelerated="false"

Reference

Another Tricks

For animation functionality you may visit

http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

Fastest way to Remove Duplicate Value from a list<> by lambda

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

DataGridView - Focus a specific cell

you can set Focus to a specific Cell by setting Selected property to true

dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;

to avoid Multiple Selection just set

dataGridView1.MultiSelect = false;

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

How to avoid the "Circular view path" exception with Spring MVC test

I am using Spring Boot to try and load a webpage, not test, and had this problem. My solution was a bit different than those above considering the slightly different circumstances. (although those answers helpled me understand.)

I simply had to change my Spring Boot starter dependency in Maven from:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
</dependency>

to:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Just changing the 'web' to 'thymeleaf' fixed the problem for me.

Python ValueError: too many values to unpack

self.materials is a dict and by default you are iterating over just the keys (which are strings).

Since self.materials has more than two keys*, they can't be unpacked into the tuple "k, m", hence the ValueError exception is raised.

In Python 2.x, to iterate over the keys and the values (the tuple "k, m"), we use self.materials.iteritems().

However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:

for m in self.materials.itervalues():

In Python 3.x, prefer dict.values() (which returns a dictionary view object):

for m in self.materials.values():

No module named setuptools

For Python Run This Command

apt-get install -y python-setuptools

For Python 3.

apt-get install -y python3-setuptools

How to generate unique id in MySQL?

To get unique and random looking tokens you could just encrypt your primary key i.e.:

SELECT HEX(AES_ENCRYPT(your_pk,'your_password')) AS 'token' FROM your_table;

This is good enough plus its reversable so you'd not have to store that token in your table but to generate it instead.

Another advantage is once you decode your PK from that token you do not have to do heavy full text searches over your table but simple and quick PK search.

Theres one small problem though. MySql supports different block encryption modes which if changed will completely change your token space making old tokens useless...

To overcome this one could set that variable before token generated i.e.:

SET block_encryption_mode = 'aes-256-cbc';

However that a bit waste... The solution for this is to attach an encryption mode used marker to the token:

SELECT CONCAT(CONV(CRC32(@@GLOBAL.block_encryption_mode),10,35),'Z',HEX(AES_ENCRYPT(your_pk,'your_password'))) AS 'token' FROM your_table;

Another problem may come up if you wish to persist that token in your table on INSERT because to generate it you need to know primary_key for the record which was not inserted yet... Ofcourse you might just INSERT and then UPDATE with LAST_INSERT_ID() but again - theres a better solution:

INSERT INTO your_table ( token )
SELECT CONCAT(CONV(CRC32(@@GLOBAL.block_encryption_mode),10,35),'Z',HEX(AES_ENCRYPT(your_pk,'your_password'))) AS 'token'
FROM information_schema.TABLES 
WHERE  TABLE_SCHEMA = DATABASE() AND TABLE_NAME = "your_table";

One last but not least advantage of this solution is you can easily replicate it in php, python, js or any other language you might use.

is there something like isset of php in javascript/jQuery?

Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

Updating records codeigniter

In your_controller write this...

public function update_title() 
{   
    $data = array
      (
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')
      );

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
    {
        // update successful...
    }
    else
    {
        // update not successful...
    }

}

While in your_model...

public function update_title($data)
{
   $this->db->set('table_title',$data['title'])
         ->where('table_id',$data['table_id'])
        ->update('your_table');
}

This will works fine...

How to do logging in React Native?

Chrome Devtool is the best and easiest way for logging and debugging.

Powershell remoting with ip-address as target

The error message is giving you most of what you need. This isn't just about the TrustedHosts list; it's saying that in order to use an IP address with the default authentication scheme, you have to ALSO be using HTTPS (which isn't configured by default) and provide explicit credentials. I can tell you're at least not using SSL, because you didn't use the -UseSSL switch.

Note that SSL/HTTPS is not configured by default - that's an extra step you'll have to take. You can't just add -UseSSL.

The default authentication mechanism is Kerberos, and it wants to see real host names as they appear in AD. Not IP addresses, not DNS CNAME nicknames. Some folks will enable Basic authentication, which is less picky - but you should also set up HTTPS since you'd otherwise pass credentials in cleartext. Enable-PSRemoting only sets up HTTP.

Adding names to your hosts file won't work. This isn't an issue of name resolution; it's about how the mutual authentication between computers is carried out.

Additionally, if the two computers involved in this connection aren't in the same AD domain, the default authentication mechanism won't work. Read "help about_remote_troubleshooting" for information on configuring non-domain and cross-domain authentication.

From the docs at http://technet.microsoft.com/en-us/library/dd347642.aspx

HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
-----------------------------------------------------
    ERROR:  The WinRM client cannot process the request. If the
    authentication scheme is different from Kerberos, or if the client
    computer is not joined to a domain, then HTTPS transport must be used
    or the destination machine must be added to the TrustedHosts
    configuration setting.

The ComputerName parameters of the New-PSSession, Enter-PSSession and
Invoke-Command cmdlets accept an IP address as a valid value. However,
because Kerberos authentication does not support IP addresses, NTLM
authentication is used by default whenever you specify an IP address. 

When using NTLM authentication, the following procedure is required
for remoting.

1. Configure the computer for HTTPS transport or add the IP addresses
   of the remote computers to the TrustedHosts list on the local
   computer.

   For instructions, see "How to Add a Computer to the TrustedHosts
   List" below.


2. Use the Credential parameter in all remote commands.

   This is required even when you are submitting the credentials
   of the current user.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py

It does what I need, little documentation, but feel free to copy ideas from there ;-)

(Seems to work fine with my backups at least.)

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I had this problem when I wanted to make a vnc connection via a tunnel. But the vncserver was not running. I solved it by opening the channel on the remote machine with vncserver :3.

See last changes in svn

Open you working copy folder in console (terminal) and choose commands below. To see last changes: If you have commited last changes use:

svn diff -rPREV

If you left changes in working copy (that's bad practice) than use:

svn diff

To see log of commits: If you're working in branch:

svn log --stop-on-copy 

If you're working with trunk:

svn log | head

or just

svn log

How to clear radio button in Javascript?

In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}

How can I see if a Perl hash already has a certain key?

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

Concept behind putting wait(),notify() methods in Object class

Answer to your first question is As every object in java has only one lock(monitor) andwait(),notify(),notifyAll() are used for monitor sharing thats why they are part of Object class rather than Threadclass.

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays have numerical indexes. So,

a = new Array();
a['a1']='foo';
a['a2']='bar';

and

b = new Array(2);
b['b1']='foo';
b['b2']='bar';

are not adding elements to the array, but adding .a1 and .a2 properties to the a object (arrays are objects too). As further evidence, if you did this:

a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length);   // outputs zero because there are no items in the array

Your third option:

c=['c1','c2','c3'];

is assigning the variable c an array with three elements. Those three elements can be accessed as: c[0], c[1] and c[2]. In other words, c[0] === 'c1' and c.length === 3.

Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.

a = {};
a['a1']='foo';
a['a2']='bar';

It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Postgres: SQL to list table foreign keys

Proper solution to the problem, using information_schema, working with multi column keys, joining columns of different names in both tables correctly and also compatible with ms sqlsever:

select fks.TABLE_NAME as foreign_key_table_name
, fks.CONSTRAINT_NAME as foreign_key_constraint_name
, kcu_foreign.COLUMN_NAME as foreign_key_column_name
, rc.UNIQUE_CONSTRAINT_NAME as primary_key_constraint_name
, pks.TABLE_NAME as primary_key_table_name
, kcu_primary.COLUMN_NAME as primary_key_column_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS fks -- foreign keys
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu_foreign -- the columns of the above keys
    on fks.TABLE_CATALOG = kcu_foreign.TABLE_CATALOG
    and fks.TABLE_SCHEMA = kcu_foreign.TABLE_SCHEMA
    and fks.TABLE_NAME = kcu_foreign.TABLE_NAME
    and fks.CONSTRAINT_NAME = kcu_foreign.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc -- referenced constraints
    on rc.CONSTRAINT_CATALOG = fks.CONSTRAINT_CATALOG
    and rc.CONSTRAINT_SCHEMA = fks.CONSTRAINT_SCHEMA
    and rc.CONSTRAINT_NAME = fks.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pks -- primary keys (referenced by fks)
    on rc.UNIQUE_CONSTRAINT_CATALOG = pks.CONSTRAINT_CATALOG
    and rc.UNIQUE_CONSTRAINT_SCHEMA = pks.CONSTRAINT_SCHEMA
    and rc.UNIQUE_CONSTRAINT_NAME = pks.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu_primary
    on pks.TABLE_CATALOG = kcu_primary.TABLE_CATALOG
    and pks.TABLE_SCHEMA = kcu_primary.TABLE_SCHEMA
    and pks.TABLE_NAME = kcu_primary.TABLE_NAME
    and pks.CONSTRAINT_NAME = kcu_primary.CONSTRAINT_NAME
    and kcu_foreign.ORDINAL_POSITION = kcu_primary.ORDINAL_POSITION -- this joins the columns
where fks.TABLE_SCHEMA = 'dbo' -- replace with schema name
and fks.TABLE_NAME = 'your_table_name' -- replace with table name
and fks.CONSTRAINT_TYPE = 'FOREIGN KEY'
and pks.CONSTRAINT_TYPE = 'PRIMARY KEY'
order by fks.constraint_name, kcu_foreign.ORDINAL_POSITION

Note: There are some differences between potgresql and sqlserver implementations of information_schema which make the top answer give different results on the two systems - one shows column names for the foreign key table the other for the primary key table. For this reason I decided to use KEY_COLUMN_USAGE view instead.

What is token-based authentication?

I think it's well explained here -- quoting just the key sentences of the long article:

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

In other words: add one level of indirection for authentication -- instead of having to authenticate with username and password for each protected resource, the user authenticates that way once (within a session of limited duration), obtains a time-limited token in return, and uses that token for further authentication during the session.

Advantages are many -- e.g., the user could pass the token, once they've obtained it, on to some other automated system which they're willing to trust for a limited time and a limited set of resources, but would not be willing to trust with their username and password (i.e., with every resource they're allowed to access, forevermore or at least until they change their password).

If anything is still unclear, please edit your question to clarify WHAT isn't 100% clear to you, and I'm sure we can help you further.

What is the use of GO in SQL Server Management Studio & Transact SQL?

Since Management Studio 2005 it seems that you can use GO with an int parameter, like:

INSERT INTO mytable DEFAULT VALUES
GO 10

The above will insert 10 rows into mytable. Generally speaking, GO will execute the related sql commands n times.

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

Center fixed div with dynamic width (CSS)

You can center a fixed or absolute positioned element setting right and left to 0, and then margin-left & margin-right to auto as if you were centering a static positioned element.

#example {
    position: fixed;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;
}

See this example working on this fiddle.

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

How to redirect output of systemd service to a file

Short answer:

StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log

If you don't want the files to be cleared every time the service is run, use append instead:

StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log

scp from Linux to Windows

To send a file from windows to linux system

scp path-to-file user@ipaddress:/path-to-destination

Example:

scp C:/Users/adarsh/Desktop/Document.txt [email protected]:/tmp

keep in mind that there need to use forward slash(/) inplace of backward slash(\) in for the file in windows path else it will show an error

C:UsersadarshDesktopDocument.txt: No such file or directory

. After executing scp command you will ask for password of root user in linux machine. There you GO...

To send a file from linux to windows system

scp -r user@ipaddress:/path-to-file path-to-destination

Example:

scp -r [email protected]:/tmp/Document.txt C:/Users/adarsh/Desktop/

and provide your linux password. only one you have to add in this command is -r. Thanks.

Creating a system overlay window (always on top)

@Sarwar Erfan's answer does not work any longer as Android does not allow adding view with WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY to window to be touchable anymore not with even WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH.

I found solution to this problem. You can check it out in following question

When adding view to window with WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, it is not getting touch event

Shell script variable not empty (-z option)

Why would you use -z? To test if a string is non-empty, you typically use -n:

if test -n "$errorstatus"; then
  echo errorstatus is not empty
fi

Hibernate Error: a different object with the same identifier value was already associated with the session

If left an expressions tab in my IDE open which was making a hibernate get call on the object causing this exception. I was trying to delete this same object. Also I had a breakpoint on the delete call which seems to be necessary to get this error to happen. Simply making another expressions tab to be the front tab or changing the setting so that the ide does not stop on breakpoints solved this problem.

String representation of an Enum

I know pretty well that this question have already been answered and that the OP is already happy with the accepted answer. But I found most of the answers, including the accepted one, to be a little bit more complicated.

I have a project which gave me a situation like this and I was able to achieve it this way.

First, you have to consider the casing of your enum names:

public enum AuthenticationMethod
{
    Forms = 1,
    WindowsAuthentication = 2,
    SingleSignOn = 3
}

Then, have this extension:

using System.Text.RegularExpression;

public static class AnExtension
{
    public static string Name(this Enum value)
    {
        string strVal = value.ToString();
        try
        {
            return Regex.Replace(strVal, "([a-z])([A-Z])", "$1 $2");
        }
        catch
        {
        }
        return strVal;
    }
}

Through this you can turn your every enum name to its string representation with each word separated with a space. Ex:

AuthenticationMethod am = AuthenticationMethod.WindowsAuthentication;
MessageBox.Show(am.Name());

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

Codeigniter LIKE with wildcard(%)

Searching multiple fields at once can be done like so...

function search($search)
{
    $sql = "SELECT * FROM some_table
    WHERE UPPER(a_name) LIKE ?
    OR
    UPPER(a_full_name) LIKE ?
    OR
    UPPER(a_city) LIKE ?
    OR
    UPPER(a_code) LIKE ?
    ";
    $arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
    $r = $this->db->query($sql, $arr);
    return $r;
}

function wrapLIKE($string)
{
    return strtoupper("%$string%");
}

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

java: How can I do dynamic casting of a variable from one type to another?

It works and there's even a common pattern for your approach: the Adapter pattern. But of course, (1) it does not work for casting java primitives to objects and (2) the class has to be adaptable (usually by implementing a custom interface).

With this pattern you could do something like:

Wolf bigBadWolf = new Wolf();
Sheep sheep = (Sheep) bigBadWolf.getAdapter(Sheep.class);

and the getAdapter method in Wolf class:

public Object getAdapter(Class clazz) {
  if (clazz.equals(Sheep.class)) {
    // return a Sheep implementation
    return getWolfDressedAsSheep(this);
  }

  if (clazz.equals(String.class)) {
    // return a String
    return this.getName();
  }

  return null; // not adaptable
}

For you special idea - that is impossible. You can't use a String value for casting.

Enterprise app deployment doesn't work on iOS 7.1

It is true, going forward you are expected to do all OTA deployments over https going forward with iOS7.1. Shame on Apple for not documenting this.

For those of you that are looking for a better in-house solution than relying on dropbox or having to fork out cash for a certificate you can have a solution if you follow the steps outlined in tip #5 here: http://blog.httpwatch.com/2013/12/12/five-tips-for-using-self-signed-ssl-certificates-with-ios/

The gist of it is this:

  • Create your own CA Authority certificate that you can install on the device that is fully trusted (I installed by simply emailing it)
  • Create the key/cer pair against the root certificate and install it on your server
  • Make sure your webserver utilizes the key/cer pair that matches the CA Authority root certificate
  • At this point you should be able to install your apps as usual over https
  • All of this can be accomplished on OSX using openssl which is already installed by default

This is not the same as just doing a self-signed certificate, in this solution you are also acting as your own private Certificate Authority. If your root certificate that is installed on your Apple device is not marked as Trusted (green) then something is wrong. Do it over.

This absolutely works.

Update: 3/13/2014 - I have provided a small command line utility that simplifies this entire process. You can get it at: https://github.com/deckarep/EasyCert/releases

How to auto-generate a C# class file from a JSON string

Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.

Visual Studio 2013 onwards have this built-in.

Visual Studio Paste JSON as Classes screenshot (Image courtesy: robert.muehsig)

Maintain aspect ratio of div but fill screen width and height in CSS?

here a solution based on @Danield solution, that works even within a div.

In that example, I am using Angular but it can quickly move to vanilla JS or another framework.

The main idea is just to move the @Danield solution within an empty iframe and copy the dimensions after iframe window size changes.

That iframe has to fit dimensions with its father element.

https://stackblitz.com/edit/angular-aspect-ratio-by-iframe?file=src%2Findex.html

Here a few screenshots:

enter image description here

enter image description here

enter image description here

Rolling back local and remote git repository by 1 commit

Here's an updated version of the procedure which is safer.

git reset --hard HEAD^ 
git push --force-with-lease

git push -f will indiscriminately replace the remote repository with your own changes. If someone else has pushed changes they will be lost. git push --force-with-lease will only push your rebase if the repository is as you expect. If someone else has already pushed your push will fail.

See –force considered harmful; understanding git’s –force-with-lease.

I recommend aliasing this as repush = push --force-with-lease.

What if somebody has already pulled the repo? What would I do then?

Tell them to git pull --rebase=merges. Instead of a git fetch origin and git merge origin/master it will git fetch origin and git rebase -r origin/master. This will rewrite any of their local changes to master on top of the new rebased origin/master. -r will preserve any merges they may have made.

I recommend making this the default behavior for pulling. It is safe, will handle other's rebasing, and results in less unnecessary merges.

[pull]
        rebase = merges

TypeError: window.initMap is not a function

your call back method probably is not globally accessible. in my case I'd used transpoiled ES6 codes via webpack which caused my callback method not being global anymore.

Try to attach your callback method explicitly to window like so right after your callback method declaration and see the result

window.initMap = initMap;

it worked for me.

How to run (not only install) an android application using .apk file?

I put this in my makefile, right the next line after adb install ...

adb shell monkey -p `cat .identifier` -c android.intent.category.LAUNCHER 1

For this to work there must be a .identifier file with the app's bundle identifier in it, like com.company.ourfirstapp

No need to hunt activity name.

rsync copy over only certain types of files using include option

I think --include is used to include a subset of files that are otherwise excluded by --exclude, rather than including only those files. In other words: you have to think about include meaning don't exclude.

Try instead:

rsync -zarv  --include "*/" --exclude="*" --include="*.sh" "$from" "$to"

For rsync version 3.0.6 or higher, the order needs to be modified as follows (see comments):

rsync -zarv --include="*/" --include="*.sh" --exclude="*" "$from" "$to"

Adding the -m flag will avoid creating empty directory structures in the destination. Tested in version 3.1.2.

So if we only want *.sh files we have to exclude all files --exclude="*", include all directories --include="*/" and include all *.sh files --include="*.sh".

You can find some good examples in the section Include/Exclude Pattern Rules of the man page

Android SeekBar setOnSeekBarChangeListener

onProgressChanged is called every time you move the cursor.

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    textView.setText(String.valueOf(new Integer(progress)));        
}

so textView should show the progress and alter always if the seekbar is being moved.

Convert string to BigDecimal in java

May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

This is my function (based on this) to clean the dataset of nan, Inf, and missing cells (for skewed datasets):

import pandas as pd

def clean_dataset(df):
    assert isinstance(df, pd.DataFrame), "df needs to be a pd.DataFrame"
    df.dropna(inplace=True)
    indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)
    return df[indices_to_keep].astype(np.float64)

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

python: unhashable type error

  File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
    counter[row[11]]+=1
TypeError: unhashable type: 'list'

row[11] is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.

Do this

counter[tuple(row[11])]+=1

Also, simplify.

d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]

React - How to force a function component to render?

None of these gave me a satisfactory answer so in the end I got what I wanted with the key prop, useRef and some random id generator like shortid.

Basically, I wanted some chat application to play itself out the first time someone opens the app. So, I needed full control over when and what the answers are updated with the ease of async await.

Example code:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// ... your JSX functional component, import shortid somewhere

const [render, rerender] = useState(shortid.generate())

const messageList = useRef([
    new Message({id: 1, message: "Hi, let's get started!"})
])

useEffect(()=>{
    await sleep(500)
    messageList.current.push(new Message({id: 1, message: "What's your name?"}))
    // ... more stuff
    // now trigger the update
    rerender(shortid.generate())
}, [])

// only the component with the right render key will update itself, the others will stay as is and won't rerender.
return <div key={render}>{messageList.current}</div> 

In fact this also allowed me to roll something like a chat message with a rolling .

const waitChat = async (ms) => {
    let text = "."
    for (let i = 0; i < ms; i += 200) {
        if (messageList.current[messageList.current.length - 1].id === 100) {
            messageList.current = messageList.current.filter(({id}) => id !== 100)
        }
        messageList.current.push(new Message({
            id: 100,
            message: text
        }))
        if (text.length === 3) {
            text = "."
        } else {
            text += "."
        }
        rerender(shortid.generate())
        await sleep(200)
    }
    if (messageList.current[messageList.current.length - 1].id === 100) {
        messageList.current = messageList.current.filter(({id}) => id !== 100)
    }
}

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

How do I connect to a MySQL Database in Python?

MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.

Reading Data From Database and storing in Array List object

Instead ofnull, use CustomerDTO customers =new CustomerDTO()`;

CustomerDTO customer = null;


  private static List<Author> getAllAuthors() {
    initConnection();
    List<Author> authors = new ArrayList<Author>();
    Author author = new Author();
    try {
        stmt = (Statement) conn.createStatement();
        String str = "SELECT * FROM author";
        rs = (ResultSet) stmt.executeQuery(str);

        while (rs.next()) {
            int id = rs.getInt("nAuthorId");
            String name = rs.getString("cAuthorName");
            author.setnAuthorId(id);
            author.setcAuthorName(name);
            authors.add(author);
            System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
        }
        rs.close();
        closeConnection();
    } catch (Exception e) {
        System.out.println(e);
    }
    return authors;
}

android - save image into gallery

According to this course, the correct way to do this is:

Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    )

This will give you the root path for the gallery directory.

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

How to fully clean bin and obj folders within Visual Studio?

Update: Visual Studio 2019 (Clean [bin] and [obj] before release). However I am not sure if [obj] needs to be deleted. Be aware there is nuget package configuration placed too. You can remove the second line if you think so.

<Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition="'$(Configuration)' == 'Release'">
  <!--remove bin-->
  <Exec Command="rd /s /q &quot;$(ProjectDir)$(BaseOutputPath)&quot; &amp;&amp; ^" />
  <!--remove obj-->
  <Exec Command="rd /s /q &quot;$(BaseIntermediateOutputPath)Release&quot;" />
</Target>

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

SQL Server 2005 Using CHARINDEX() To split a string

I wouldn't exactly say it is easy or obvious, but with just two hyphens, you can reverse the string and it is not too hard:

with t as (select 'LD-23DSP-1430' as val)
select t.*,
       LEFT(val, charindex('-', val) - 1),
   SUBSTRING(val, charindex('-', val)+1, len(val) - CHARINDEX('-', reverse(val)) - charindex('-', val)),
       REVERSE(LEFT(reverse(val), charindex('-', reverse(val)) - 1))
from t;

Beyond that and you might want to use split() instead.

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

NLS_NUMERIC_CHARACTERS setting for decimal

To know SESSION decimal separator, you can use following SQL command:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select SUBSTR(value,1,1) as "SEPARATOR"
      ,'using NLS-PARAMETER' as "Explanation"
  from nls_session_parameters
  where parameter = 'NLS_NUMERIC_CHARACTERS'

UNION ALL

select SUBSTR(0.5,1,1) as "SEPARATOR" 
      ,'using NUMBER IMPLICIT CASTING' as "Explanation"
  from DUAL;

The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS table. The decimal separator is the first character of the returned value.

The second SELECT command convert IMPLICITELY the 0.5 rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.

The both command return same value.

I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.

To test what I say, I have used following SQL commands:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;

DECLARE
    S VARCHAR2(10) := '?';
BEGIN

    select .5 INTO S from dual;

    DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/

The shorter command to know decimal separator is:

SELECT .5 FROM DUAL;

That return 0,5 if decimal separator is a COMMA and 0.5 if decimal separator is a POINT.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

PUT compile 'de.hdodenhof:circleimageview:2.0.0' IN Gradle Dependencies and put this code in nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/lib/org.mainsoft.navigationdrawer"

    android:gravity="bottom"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="@drawable/background_material_red"
    android:orientation="vertical">

<de.hdodenhof.circleimageview.CircleImageView

    android:id="@+id/profile_image"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:src="@drawable/profile"
    app:border_color="#FF000000"
    android:layout_marginLeft="24dp"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginStart="24dp" />

</LinearLayout>

What is the maximum possible length of a .NET string?

The max length of a string on my machine is 1,073,741,791.

You see, Strings aren't limited by integer as is commonly believed.

Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.

Now, here's something you're welcome to try yourself.

Create a new C# console app in Visual Studio and then copy/paste the main method here:

static void Main(string[] args)
{
    Console.WriteLine("String test, by Nicholas John Joseph Taylor");

    Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");

    Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");

    Console.WriteLine("\nThe test starts ...now:\n");

    int Length = 0;

    string s = "";

    int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.

    LoopPoint:

    // Make a string appendage the length of the value of Increment

    StringBuilder StringAppendage = new StringBuilder();

    for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
    {
        StringAppendage.Append("0");

    }

    // Repeatedly append string appendage until an out of memory exception is thrown.

    try
    {
        if (Increment > 0)
            while (Length < int.MaxValue)
            {
                Length += Increment;

                s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment

                Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));

            }

    }
    catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
    {
        Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Length -= Increment;

        Increment /= 10;

        Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");

    }
    catch (Exception ex2)
    {
        Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Console.WriteLine("Press a key to continue...");

        Console.ReadKey();

    }

    if (Increment > 0)
    {
        goto LoopPoint;

    }

    Console.WriteLine("Test complete.");

    Console.WriteLine("\nThe max length of a string is " + s.Length + ".");

    Console.WriteLine("\nPress any key to continue.");

    Console.ReadKey();

}

My results were as follows:

String test, by Nicholas John Joseph Taylor

Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.

This is a quickish test to narrow down results to find the max supported length of a string.

The test starts ...now:

s.Length = 1000000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.

The max length of a string is 1073741791.

Press any key to continue.

The max length of a string on my machine is 1073741791.

I'd appreciate it very much if people could post their results as a comment below.

It will be interesting to learn if people get the same or different results.

How to downgrade tensorflow, multiple versions possible?

Is it possible to have multiple version of tensorflow on the same OS?

Yes, you can use python virtual environments for this. From the docs:

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

After you have install virtualenv (see the docs), you can create a virtual environment for the tutorial and install the tensorflow version you need in it:

PATH_TO_PYTHON=/usr/bin/python3.5
virtualenv -p $PATH_TO_PYTHON my_tutorial_env 
source my_tutorial_env/bin/activate # this activates your new environment
pip install tensorflow==1.1

PATH_TO_PYTHON should point to where python is installed on your system. When you want to use the other version of tensorflow execute:

deactivate my_tutorial_env

Now you can work again with the tensorflow version that was already installed on your system.

Remove scrollbar from iframe

Try adding scrolling="no" attribute like below:

_x000D_
_x000D_
<iframe frameborder="0" scrolling="no" style="height:380px;width:6000px;border:none;" src='https://yoururl'></iframe>
_x000D_
_x000D_
_x000D_

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Is it possible to make desktop GUI application in .NET Core?

I have been searching for this for ages now and none of the solution above are to my satisfaction.

I ended up working with https://github.com/mellinoe/ImGui.NET for now.

I can confirm it works at least across macos and win10 and claims to be compatible with linux.

Leaving this here in case it can help someone.

enter image description here

Difference between session affinity and sticky session?

They are Synonyms. No Difference At all

Sticky Session / Session Affinity:

Affinity/Stickiness/Contact between user session and, the server to which user request is sent is retained.

Customize UITableView header section

swif 4.2

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }

    header.textLabel?.textAlignment = .center // for all sections

    switch section {
    case 1:  //only section No.1
        header.textLabel?.textColor = .black
    case 3:  //only section No.3
        header.textLabel?.textColor = .red
    default: //
        header.textLabel?.textColor = .yellow
    }
}

Ternary operator in AngularJS templates

While you can use the condition && if-true-part || if-false-part-syntax in older versions of angular, the usual ternary operator condition ? true-part : false-part is available in Angular 1.1.5 and later.

Assigning default values to shell variables with a single command in bash

Then there's the way of expressing your 'if' construct more tersely:

FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

Is JavaScript guaranteed to be single-threaded?

Try to nest two setTimeout functions within each other and they will behave multithreaded (ie; the outer timer won't wait for the inner one to complete before executing its function).

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

customize Android Facebook Login button

This is very simple. Add a button in the layout file like

<Button
   android:layout_width="200dp"
   android:layout_height="wrap_content"
   android:text="Login with facebook"
   android:textColor="#ffff"
   android:layout_gravity="center"
   android:textStyle="bold"
   android:onClick="fbLogin"
   android:background="@color/colorPrimary"/>

And in the onClick place the LoginManager's registercallback() method Becuse the this method automatically executes.

  public void fbLogin(View view)
{
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts" , "AccessToken"));
    LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>()
            {
                @Override
                public void onSuccess(LoginResult loginResult)
                {
                    // App code
                }

                @Override
                public void onCancel()
                {
                    // App code
                }

                @Override
                public void onError(FacebookException exception)
                {
                    // App code
                }
            });
}

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

specifying goal in pom.xml

Add the goal like -

 <build>
        <defaultGoal>install</defaultGoal>
        <!-- Source directory configuration -->
        <sourceDirectory>src</sourceDirectory>
</build>

This will solve the issue

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

Transparent scrollbar with css

Embed this code in your css.

::-webkit-scrollbar {
    width: 0px;
}

/* Track */

::-webkit-scrollbar-track {
    -webkit-box-shadow: none;
}

/* Handle */

::-webkit-scrollbar-thumb {
    background: white;
    -webkit-box-shadow: none;
}

::-webkit-scrollbar-thumb:window-inactive {
    background: none;
}

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!

When you add the first fragment you should use something like this:

getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 

or

getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()

And when you want to show Fragments B,C and D you use this:

getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()

and other letters....

To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.

You're welcome ;)

How can I use a reportviewer control in an asp.net mvc 3 razor view?

I am using ASP.NET MVC3 with SSRS 2008 and I couldn't get @Adrian's to work 100% for me when trying to get reports from a remote server.

Finally, I found that I needed to change the Page_Load method in ViewUserControl1.ascx to look like this:

ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();

I had been missing the ProcessingMode.Remote.

References:

http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer

Find unique rows in numpy.array

Lets get the entire numpy matrix as a list, then drop duplicates from this list, and finally return our unique list back into a numpy matrix:

matrix_as_list=data.tolist() 
matrix_as_list:
[[1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0]]

uniq_list=list()
uniq_list.append(matrix_as_list[0])

[uniq_list.append(item) for item in matrix_as_list if item not in uniq_list]

unique_matrix=np.array(uniq_list)
unique_matrix:
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])

Display number always with 2 decimal places in <input>

AngularJS - Input number with 2 decimal places it could help... Filtering:

  1. Set the regular expression to validate the input using ng-pattern. Here I want to accept only numbers with a maximum of 2 decimal places and with a dot separator.
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal | number : 2" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />

Reading forward this was pointed on the next answer ng-model="myDecimal | number : 2".

ITextSharp insert text to an existing pdf

In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:

 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Understanding the set() function

As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted on the set:

>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]

How do I use disk caching in Picasso?

This is what I did. Works well.

First add the OkHttp to the gradle build file of the app module:

compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

Then make a class extending Application

import android.app.Application;

import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;

public class Global extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        Picasso.Builder builder = new Picasso.Builder(this);
        builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
        Picasso built = builder.build();
        built.setIndicatorsEnabled(true);
        built.setLoggingEnabled(true);
        Picasso.setSingletonInstance(built);

    }
}

add it to the Manifest file as follows :

<application
        android:name=".Global"
        .. >

</application>

Now use Picasso as you normally would. No changes.

EDIT:

if you want to use cached images only. Call the library like this. I've noticed that if we don't add the networkPolicy, images won't show up in an fully offline start even if they are cached. The code below solves the problem.

Picasso.with(this)
            .load(url)
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(imageView);

EDIT #2

the problem with the above code is that if you clear cache, Picasso will keep looking for it offline in cache and fail, the following code example looks at the local cache, if not found offline, it goes online and replenishes the cache.

Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(posts.get(position).getImageUrl())
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

What does the ^ (XOR) operator do?

^ is the Python bitwise XOR operator. It is how you spell XOR in python:

>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0

XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:

>>> 10 ^ 5
15
>>> 15 ^ 5
10

where 5 is the mask; (input XOR mask) XOR mask gives you the input again.

Is it possible to insert HTML content in XML document?

Please see this.

Text inside a CDATA section will be ignored by the parser.

http://www.w3schools.com/xml/dom_cdatasection.asp

This is will help you to understand the basics about XML

Shortest way to check for null and assign another value if not

To extend @Dave's answer...if planRec.approved_by is already a string

this.approved_by = planRec.approved_by ?? "";

What is a clean, Pythonic way to have multiple constructors in Python?

Use num_holes=None as a default, instead. Then check for whether num_holes is None, and if so, randomize. That's what I generally see, anyway.

More radically different construction methods may warrant a classmethod that returns an instance of cls.

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

DTO pattern: Best way to copy properties between two objects

You can have a look at dozer which is a

Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Another better link...

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>     

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

AngularJs: How to set radio button checked based on model

As discussed somewhat in the question comments, this is one way you could do it:

  • When you first retrieve the data, loop through all locations and set storeDefault to the store that is currently the default.
  • In the markup: <input ... ng-model="$parent.storeDefault" value="{{location.id}}">
  • Before you save the data, loop through all the merchant.storeLocations and set isDefault to false except for the store where location.id compares equal to storeDefault.

The above assumes that each location has a field (e.g., id) that holds a unique value.

Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.

Fiddle.

C++ error 'Undefined reference to Class::Function()'

Specify the Class Card for the constructor-:

void Card::Card(Card::Rank rank, Card::Suit suit) {

And also define the default constructor and destructor.

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

File being used by another process after using File.Create()

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

public static String fillString(int count,char c) {
    StringBuilder sb = new StringBuilder( count );
    for( int i=0; i<count; i++ ) {
        sb.append( c ); 
    }
    return sb.toString();
}

What is wrong?

How to change the hosts file on android

That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:

./emulator -avd myEmulatorName -partition-size 280

and then in other term window (pushing new hosts file /tmp/hosts):

./adb remount
./adb push /tmp/hosts /system/etc

Local dependency in package.json

Master project

Here is the package.json you will use for the master project:

"dependencies": {
    "express": "*",
    "somelocallib": "file:./somelocallib"
}

There, ./somelocallib is the reference to the library folder as relative to the master project package.json.

Reference: https://docs.npmjs.com/files/package.json#local-paths


Sub project

Handle your library dependencies.

In addition to running npm install, you will need to run (cd node_modules/somelocallib && npm install).

This is a known bug with NPM.

Reference: https://github.com/npm/npm/issues/1341 (seeking a more up-to-date reference)


Notes for Docker

Check in your master package.lock and your somelocallib/package.lock into your source code manager.

Then in your Dockerfile use:

FROM node:10
WORKDIR /app
# ...
COPY ./package.json ./package-lock.json ./
COPY somelocallib somelocallib
RUN npm ci
RUN (cd node_modules/zkp-utils/ && npm ci)
# ...

I use parenthesis in my (cd A && B) constructs to make the operation idempotent.

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Which Architecture patterns are used on Android?

Here is a great article on Common Design Patterns for Android:

Creational patterns:

  • Builder (e.g. AlertDialog.Builder)
  • Dependency Injection (e.g. Dagger 2)
  • Singleton

Structural patterns:

  • Adapter (e.g. RecyclerView.Adapter)
  • Facade (e.g. Retrofit)

Behavioral patterns:

  • Command (e.g. EventBus)
  • Observer (e.g. RxAndroid)
  • Model View Controller
  • Model View ViewModel (similar to the MVC pattern above)

How to merge rows in a column into one cell in excel?

For Excel 2011 on Mac it's different. I did it as a three step process.

  1. Create a column of values in column A.
  2. In column B, to the right of the first cell, create a rule that uses the concatenate function on the column value and ",". For example, assuming A1 is the first row, the formula for B1 is =B1. For the next row to row N, the formula is =Concatenate(",",A2). You end up with:
QA
,Sekuli
,Testing
,Applitools
,Visual Testing
,Test Automation
,Selenium
  1. In column C create a formula that concatenates all previous values. Because it is additive you will get all at the end. The formula for cell C1 is =B1. For all other rows to N, the formula is =Concatenate(C1,B2). And you get:
QA,Sekuli
QA,Sekuli,Testing
QA,Sekuli,Testing,Applitools
QA,Sekuli,Testing,Applitools,Visual Testing
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium

The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

View is the superclass for all widgets and the OnClickListener interface belongs to this class. All widgets inherit this. View.OnClickListener is the same as OnClickListener. You would have to override the onClick(View view) method from this listener to achieve the action that you want for your button.

To tell Android to listen to click events for a widget, you need to do:

widget.setOnClickListener(this); // If the containing class implements the interface
// Or you can do the following to set it for each widget individually
widget.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something here
    }
});

The 'View' parameter passed in the onClick() method simply lets Android know that a view has been clicked. It can be a Button or a TextView or something else. It is up to you to set an OnClickListener for every widget or to simply make the class containing all these widgets implement the interface. In this case you will have a common onClick() method for all the widgets and all you have to do is to check the id of the view that is passed into the method and then match that against the id for each element that you want and take action for that element.

pycharm running way slow

Every performance problem with PyCharm is unique, a solution that helps to one person will not work for another. The only proper way to fix your specific performance problem is by capturing the CPU profiler snapshot as described in this document and sending it to PyCharm support team, either by submitting a ticket or directly into the issue tracker.

After the CPU snapshot is analyzed, PyCharm team will work on a fix and release a new version which will (hopefully) not be affected by this specific performance problem. The team may also suggest you some configuration change or workaround to remedy the problem based on the analysis of the provided data.

All the other "solutions" (like enabling Power Save mode and changing the highlighting level) will just hide the real problems that should be fixed.

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Understanding MongoDB BSON Document size limit

First off, this actually is being raised in the next version to 8MB or 16MB ... but I think to put this into perspective, Eliot from 10gen (who developed MongoDB) puts it best:

EDIT: The size has been officially 'raised' to 16MB

So, on your blog example, 4MB is actually a whole lot.. For example, the full uncompresses text of "War of the Worlds" is only 364k (html): http://www.gutenberg.org/etext/36

If your blog post is that long with that many comments, I for one am not going to read it :)

For trackbacks, if you dedicated 1MB to them, you could easily have more than 10k (probably closer to 20k)

So except for truly bizarre situations, it'll work great. And in the exception case or spam, I really don't think you'd want a 20mb object anyway. I think capping trackbacks as 15k or so makes a lot of sense no matter what for performance. Or at least special casing if it ever happens.

-Eliot

I think you'd be pretty hard pressed to reach the limit ... and over time, if you upgrade ... you'll have to worry less and less.

The main point of the limit is so you don't use up all the RAM on your server (as you need to load all MBs of the document into RAM when you query it.)

So the limit is some % of normal usable RAM on a common system ... which will keep growing year on year.

Note on Storing Files in MongoDB

If you need to store documents (or files) larger than 16MB you can use the GridFS API which will automatically break up the data into segments and stream them back to you (thus avoiding the issue with size limits/RAM.)

Instead of storing a file in a single document, GridFS divides the file into parts, or chunks, and stores each chunk as a separate document.

GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.

You can use this method to store images, files, videos, etc in the database much as you might in a SQL database. I have used this to even store multi gigabyte video files.

Android - implementing startForeground for a service?

If you want to make IntentService a Foreground Service

then you should override onHandleIntent()like this

Override
protected void onHandleIntent(@Nullable Intent intent) {


    startForeground(FOREGROUND_ID,getNotification());     //<-- Makes Foreground

   // Do something

    stopForeground(true);                                // <-- Makes it again a normal Service                         

}

How to make notification ?

simple. Here is the getNotification() Method

public Notification getNotification()
{

    Intent intent = new Intent(this, SecondActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);


    NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
    foregroundNotification.setOngoing(true);

    foregroundNotification.setContentTitle("MY Foreground Notification")
            .setContentText("This is the first foreground notification Peace")
            .setSmallIcon(android.R.drawable.ic_btn_speak_now)
            .setContentIntent(pendingIntent);


    return foregroundNotification.build();
}

Deeper Understanding

What happens when a service becomes a foreground service

This happens

enter image description here

What is a foreground Service ?

A foreground service,

  • makes sure that user is actively aware of that something is going on in the background by providing the notification.

  • (most importantly) is not killed by System when it runs low on memory

A use case of foreground service

Implementing song download functionality in a Music App

Why do I get a SyntaxError for a Unicode escape in my file path?

I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.

In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.

Getting a machine's external IP address with Python

If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.

My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Find CRLF in Notepad++

I was totally unable to do this in NP v6.9. I found it easy enough on Msoft Word (2K).

Open the doc, go to edit->replace.

Then in the bottom of the search box, click "more" then find the "Special" button and they have several things for you. For Dos style, I used the "paragraph" one. This is a cr lf pair in windows land.

Check if selected dropdown value is empty using jQuery

Try this it will work --

if($('#EventStartTimeMin').val() === " ") {

    alert("Please enter start time!");

}

How do I find the PublicKeyToken for a particular dll?

I use Windows Explorer, navigate to C:\Windows\assembly , find the one I need. From the Properties you can copy the PublicKeyToken.

This doesn't rely on Visual Studio or any other utilities being installed.

Can I use jQuery to check whether at least one checkbox is checked?

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }

Add Header and Footer for PDF using iTextsharp

Just add this line before opening the document (must be before):

        document.Header = new HeaderFooter(new Phrase("Header Text"), false);
        document.Open();

Access item in a list of lists

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

Setting button text via javascript

Create a text node and append it to the button element:

var t = document.createTextNode("test content");
b.appendChild(t);

How can I get a first element from a sorted list?

Matthew's answer is correct:

list.get(0);

To do what you tried:

list[0];

you'll have to wait until Java 7 is released:

devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png

Here's an interesting presentation by Mark Reinhold about Java 7

It looks like parleys site is currently down, try later :(

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

How do I force git pull to overwrite everything on every pull?

If you haven't commit the local changes yet since the last pull/clone, you can use:

git checkout *
git pull

checkout will clear your local changes with the last local commit, and pull will sincronize it to the remote repository

How to change a dataframe column from String type to Double type in PySpark?

pyspark version:

  df = <source data>
  df.printSchema()

  from pyspark.sql.types import *

  # Change column type
  df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
  df_new.printSchema()
  df_new.select("myColumn").show()

Read line with Scanner

Try to use r.hasNext() instead of r.hasNextLine():

while(r.hasNext()) {
        scan = r.next();

How to view/delete local storage in Firefox?

There is now a great plugin for Firebug that clones this nice feature in chrome. Check out:

https://addons.mozilla.org/en-US/firefox/addon/firestorage-plus/

It's developed by Nick Belhomme and updated regularly

Is there a way to detect if an image is blurry?

Matlab code of two methods that have been published in highly regarded journals (IEEE Transactions on Image Processing) are available here: https://ivulab.asu.edu/software

check the CPBDM and JNBM algorithms. If you check the code it's not very hard to be ported and incidentally it is based on the Marzialiano's method as basic feature.

How to pass boolean parameter value in pipeline to downstream jobs?

Assuming

value: update_composer

was the issue, try

value: Boolean.valueOf(update_composer)

is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job

Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.

C# delete a folder and all files and folders within that folder

Try:

System.IO.Directory.Delete(path,true)

This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.

jQuery move to anchor location on page load

Did you tried JQuery's scrollTo method? http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

$("#header").scrollToMe();

Defined Edges With CSS3 Filter Blur

Insert the image inside a with position: relative; and overflow: hidden;

HTML

<div><img src="#"></div>

CSS

div {
    position: relative;
    overflow: hidden;
}
img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
}

This also works on variable sizes elements, like dynamic div's.

How to add a JAR in NetBeans

Right click 'libraries' in the project list, then click add.

How to change background and text colors in Sublime Text 3

To view Theme files for ST3, install PackageResourceViewer via PackageControl.

Then, you can use the Ctrl + Shift + P >> PackageResourceViewer: Open Resource to view theme files.

To edit a specific background color, you need to create a new file in your user packages folder Packages/User/SublimeLinter with the same name as the theme currently applied to your sublime text file.

However, if your theme is a 3rd party theme package installed via package control, you can edit the hex value in that file directly, under background. For example:


<dict>
  <dict>
    <key>background</key>
    <string>#073642</string>
  </dict>
</dict>

Otherwise, if you are trying to modify a native sublime theme, add the following to the new file you create (named the same as the native theme, such as Monokai.sublime-color-scheme) with your color choice


{
  "globals":
  {
      "background": "rgb(5,5,5)"
  }
}

Then, you can open the file you wish the syntax / color to be applied to and then go to Syntax-Specific settings (under Preferences) and add the path of the file to the syntax specific settings file like so:


{
    "color_scheme": "Packages/User/SublimeLinter/Monokai.sublime-color-scheme"
}

Note that if you have installed a theme via package control, it probably has the .tmTheme file extension.

If you are wanting to edit the background color of the sidebar to be darker, go to Preferences > Theme > Adaptive.sublime-theme

This my answer based on my personal experience and info gleaned from the accepted answer on this page, if you'd like more information.

Bootstrap dropdown menu not working (not dropping down when clicked)

I had the same issue I remove the following script and it worked for me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

How to capture no file for fs.readFileSync()?

I prefer this way of handling this. You can check if the file exists synchronously:

var file = 'info.json';
var content = '';

// Check that the file exists locally
if(!fs.existsSync(file)) {
  console.log("File not found");
}

// The file *does* exist
else {
  // Read the file and do anything you want
  content = fs.readFileSync(file, 'utf-8');
}

Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.

How to hide column of DataGridView when using custom DataSource?

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

target="_blank" vs. target="_new"

  • _blank as a target value will spawn a new window every time,
  • _new will only spawn one new window.

Also, every link clicked with a target value of _new will replace the page loaded in the previously spawned window.

You can click here When to use _blank or _new to try it out for yourself.

Why not use tables for layout in HTML?

I'm sorry for my English but here's another reason :

I worked in some governmental organization and the number one reason to not use TABLE, is for disabled peoples. They use machines to "translate" web pages.

The problem is this "translation machine" can't read the website if it's done by TABLE. Why ? Because TABLE are for DATAS.

in fact, if you use TABLES, for each CELLS you have to specify some informations to let disabled people to know where they are in the TABLE. Imagine you have a big table and have to zoom to see only 1 cell in the screen : you have to know in which line/col you are.

So, DIV are used, and the disabled can simply read text, and don't get some weird informations about lines/cols when they don't have to be there.

I also prefer TABLE to make quick and easy templates, but I'm now used to CSS... it's powerful, but you really have to know what you are doing... :)

How do I send email with JavaScript without opening the mail client?

You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...

Java substring: 'string index out of range'

if (itemdescription != null && itemdescription.length() > 0) {
    pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38))); 
} else { 
    pstmt2.setString(3, "_"); 
}

How to extract text from a PDF file?

PyPDF2 in some cases ignores the white spaces and makes the result text a mess, but I use PyMuPDF and I'm really satisfied you can use this link for more info

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

There are 2 versions of jdk in your PATH VARIABLE jdk1.6.0_45 and jdk1.8.0_25. Try removing the first one ie. jdk1.6.0_45 from the PATH

How to convert std::string to LPCWSTR in C++ (Unicode)

The solution is actually a lot easier than any of the other suggestions:

std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();

Best of all, it's platform independent.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I solved this issue. use below taglib

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

and add jstl-1.2.jar

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Rather than changing the memory_limit value in your php.ini file, if there's a part of your code that could use a lot of memory, you could remove the memory_limit before that section runs, and then replace it after.

$limit = ini_get('memory_limit');
ini_set('memory_limit', -1);
// ... do heavy stuff
ini_set('memory_limit', $limit);

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

How to AUTO_INCREMENT in db2?

Added a few optional parameters for creating "future safe" sequences.

CREATE SEQUENCE <NAME>
  START WITH 1
  INCREMENT BY 1
  NO MAXVALUE
  NO CYCLE
  CACHE 10;

Add querystring parameters to link_to

The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

Raw SQL Query without DbSet - Entity Framework Core

With Entity Framework 6 you can execute something like below

Create Modal Class as

Public class User
{
        public int Id { get; set; }
        public string fname { get; set; }
        public string lname { get; set; }
        public string username { get; set; }
}

Execute Raw DQL SQl command as below:

var userList = datacontext.Database.SqlQuery<User>(@"SELECT u.Id ,fname , lname ,username FROM dbo.Users").ToList<User>();

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

Java - Convert image to Base64

You can create a large array and then copy it to a new array using System.arrayCopy

        int contentLength = 100000000;
        byte[] byteArray = new byte[contentLength];

        BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
        while ((bytesRead = inputStream.read()) != -1)
        {
            byteArray[count++] = (byte)bytesRead;
        }

        byte[] destArray = new byte[count];
        System.arraycopy(byteArray, 0, destArray , 0, count);

destArray will contain the information you want

Best way to do multiple constructors in PHP

I created this method to let use it not only on constructors but in methods:

My constructor:

function __construct() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('__construct',func_get_args());
    }
}

My doSomething method:

public function doSomething() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('doSomething',func_get_args());
    }
}

Both works with this simple method:

public function overloadMethod($methodName,$params){
    $paramsNumber=sizeof($params);
    //methodName1(), methodName2()...
    $methodNameNumber =$methodName.$paramsNumber;
    if (method_exists($this,$methodNameNumber)) {
        call_user_func_array(array($this,$methodNameNumber),$params);
    }
}

So you can declare

__construct1($arg1), __construct2($arg1,$arg2)...

or

methodName1($arg1), methodName2($arg1,$arg2)...

and so on :)

And when using:

$myObject =  new MyClass($arg1, $arg2,..., $argN);

it will call __constructN, where you defined N args

then $myObject -> doSomething($arg1, $arg2,..., $argM)

it will call doSomethingM, , where you defined M args;

How to display raw html code in PRE or something like it but without escaping it

You can use the xmp element, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).

Everything inside xmp is taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>.

Otherwise xmp is rendered like pre.

When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmp is treated like pre. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a pre element:

<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>

I don’t see how you could combine xmp and CDATA section to achieve so-called polyglot markup

CSS /JS to prevent dragging of ghost image?

Handle the dragstart event and return false.

ArrayList insertion and retrieval order

Yes. ArrayList is a sequential list. So, insertion and retrieval order is the same.

If you add elements during retrieval, the order will not remain the same.

How to represent empty char in Java Character class

In java there is nothing as empty character literal, in other words, '' has no meaning unlike "" which means a empty String literal

The closest you can go about representing empty character literal is through zero length char[], something like:

char[] cArr = {};         // cArr is a zero length array
char[] cArr = new char[0] // this does the same

If you refer to String class its default constructor creates a empty character sequence using new char[0]

Also, using Character.MIN_VALUE is not correct because it is not really empty character rather smallest value of type character.

I also don't like Character c = null; as a solution mainly because jvm will throw NPE if it tries to un-box it. Secondly, null is basically a reference to nothing w.r.t reference type and here we are dealing with primitive type which don't accept null as a possible value.

Assuming that in the string, say str, OP wants to replace all occurrences of a character, say 'x', with empty character '', then try using:

str.replace("x", "");