Programs & Examples On #Scribd

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

How to Bold entire row 10 example:

workSheet.Cells[10, 1].EntireRow.Font.Bold = true;    

More formally:

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;

How to Bold Specific Cell 'A10' for example:

workSheet.Cells[10, 1].Font.Bold = true;

Little more formal:

int row = 1;
int column = 1;  /// 1 = 'A' in Excel

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;

Can the Android drawable directory contain subdirectories?

One way to partially get around the problem is to use the API Level suffix. I use res/layout-v1, res/layout-v2 etc to hold multiple sub projects in the same apk. This mechanism can be used for all resource types.

Obviously, this can only be used if you are targeting API levels above the res/layout-v? you are using.

Also, watch out for the bug in Android 1.5 and 1.6. See Andoroid documentation about the API Level suffix.

How do I attach events to dynamic HTML elements with jQuery?

Sometimes doing this (the top-voted answer) is not always enough:

$('body').on('click', 'a.myclass', function() {
    // do something
});

This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.

For example:

function RefreshSomeEventListener() {
    // Remove handler from existing elements
    $("#wrapper .specific-selector").off(); 

    // Re-add event handler for all matching elements
    $("#wrapper .specific-selector").on("click", function() {
        // Handle event.
    }
}

Because it is a function, whenever I set up my listener this way, I typically call it on document ready:

$(document).ready(function() {
    // Other ready commands / code

    // Call our function to setup initial listening
    RefreshSomeEventListener();
});

Then, whenever you add some dynamically added element, call that method again:

function SomeMethodThatAddsElement() {
    // Some code / AJAX / whatever.. Adding element dynamically

    // Refresh our listener, so the new element is taken into account
    RefreshSomeEventListener();
}

Hopefully this helps!

Regards,

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me this setting was working.
In my windows 8.1 the path for php7 is

C:\user\test\tools\php7\php.exe

settings.json

 {  
 "php.executablePath":"/user/test/tools/php7/php.exe",
 "php.validate.executablePath": "/user/test/tools/php7/php.exe"
 }

see also https://github.com/microsoft/vscode/issues/533

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

Get value of a string after last slash in JavaScript

You don't need jQuery, and there are a bunch of ways to do it, for example:

var parts = myString.split('/');
var answer = parts[parts.length - 1];

Where myString contains your string.

Why does git revert complain about a missing -m option?

I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:

*   commit I want to cherry-pick (x)
|\  
| * branch I want to cherry-pick to (y)
* | 
|/  
* common parent (x)

I understand now that I want to do

git cherry-pick -m 2 mycommitsha

This is because -m 1 would merge based on the common parent where as -m 2 merges based on branch y, that is the one I want to cherry-pick to.

How to access host port from docker container

I created a docker container for doing exactly that https://github.com/qoomon/docker-host

You can then simply use container name dns to access host system e.g. curl http://dockerhost:9200

Difference between float and decimal data type

decimal is for fixed quantities like money where you want a specific number of decimal places. Floats are for storing ... floating point precision numbers.

What is the color code for transparency in CSS?

There is no transparency component of the color hex string. There is opacity, which is a float from 0.0 to 1.0.

Node.js throws "btoa is not defined" error

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

console.log(Buffer.from('Hello World!').toString('base64'));

Reverse (assuming the content you're decoding is a utf8 string):

console.log(Buffer.from(b64Encoded, 'base64').toString());

Note: prior to Node v4, use new Buffer rather than Buffer.from.

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How do I trim leading/trailing whitespace in a standard way?

These functions will modify the original buffer, so if dynamically allocated, the original pointer can be freed.

#include <string.h>

void rstrip(char *string)
{
  int l;
  if (!string)
    return;
  l = strlen(string) - 1;
  while (isspace(string[l]) && l >= 0)
    string[l--] = 0;
}

void lstrip(char *string)
{
  int i, l;
  if (!string)
    return;
  l = strlen(string);
  while (isspace(string[(i = 0)]))
    while(i++ < l)
      string[i-1] = string[i];
}

void strip(char *string)
{
  lstrip(string);
  rstrip(string);
}

CKEditor automatically strips classes from div

Another option if using drupal is simply to add the css style that you want to use. that way it does not strip out the style or class name.

so in my case under the css tab in drupal 7 simply add something like

facebook=span.icon-facebook2

also check that font-styles button is enabled

NodeJS w/Express Error: Cannot GET /

I found myself on this page as I was also receiving the Cannot GET/ message. My circumstances differed as I was using express.static() to target a folder, as has been offered in previous answers, and not a file as the OP was.

What I discovered after some digging through Express' docs is that express.static() defines its index file as index.html, whereas my file was named index.htm.

To tie this to the OP's question, there are two options:

1: Use the code suggested in other answers

app.use(express.static(__dirname));

and then rename default.htm file to index.html

or

2: Add the index property when calling express.static() to direct it to the desired index file:

app.use(express.static(__dirname, { index: 'default.htm' }));

Ways to eliminate switch in code

A switch is a pattern, whether implemented with a switch statement, if else chain, lookup table, oop polymorphism, pattern matching or something else.

Do you want to eliminate the use of the "switch statement" or the "switch pattern"? The first one can be eliminated, the second one, only if another pattern/algorithm can be used, and most of the time that is not possible or it's not a better approach to do so.

If you want to eliminate the switch statement from code, the first question to ask is where does it make sense to eliminate the switch statement and use some other technique. Unfortunately the answer to this question is domain specific.

And remember that compilers can do various optimizations to switch statements. So for example if you want to do message processing efficiently, a switch statement is pretty much the way to go. But on the other hand running business rules based on a switch statement is probably not the best way to go and the application should be rearchitected.

Here are some alternatives to switch statement :

How can you create multiple cursors in Visual Studio Code

In Visual Studio without mouse: Alt+Shift+{ Arrow }.

ERROR 1064 (42000) in MySQL

(For those coming to this question from a search engine), check that your stored procedures declare a custom delimiter, as this is the error that you might see when the engine can't figure out how to terminate a statement:

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line…

If you have a database dump and see:

DROP PROCEDURE IF EXISTS prc_test;
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;

Try wrapping with a custom DELIMITER:

DROP PROCEDURE IF EXISTS prc_test;
DELIMITER $$
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;
$$
DELIMITER ;

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I found that I initialised my slider using inline script in the body, which meant it was being called before slick.js had been loaded. I fixed using inline JS in the footer to initialise the slider after including the slick.js file.

<script type="text/javascript" src="/slick/slick.min.js"></script>
<script>
    $('.autoplay').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 4000,
    });

</script>

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I had the same problem after switching to JDK 6 to compile a dependency module, then switched but to JDK 8.
Rerun the probject and compiler complained about unsupported major.minor version. I verified the Java version it was 1,8 for both the JVM and Maven.
After many tries and googling the problem was not solved, so i though what if i restart the computer (Windows 8) ?
I did restart, rerun the project again and problem was solved :)

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Magic

a.filter(( t={}, e=>!(1-(t[e]=++t[e]|0)) )) 

O(n) performance; we assume your array is in a and it contains elements that can be cast .toString() in unique way (which is done implicity by JS in t[e]) e.g numbers=[4,5,4], strings=["aa","bb","aa"], arraysNum=[[1,2,3], [43,2,3],[1,2,3]]. Explanation here, unique values here

_x000D_
_x000D_
var a1 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6, 2], [1, 12]];_x000D_
var a2 = ['Mike', 'Adam','Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];_x000D_
var a3 = [5,6,4,9,2,3,5,3,4,1,5,4,9];_x000D_
_x000D_
let nd = (a) => a.filter((t={},e=>!(1-(t[e]=++t[e]|0)))) _x000D_
_x000D_
_x000D_
// Print_x000D_
let c= x => console.log(JSON.stringify(x));             _x000D_
c( nd(a1) );_x000D_
c( nd(a2) );_x000D_
c( nd(a3) );
_x000D_
_x000D_
_x000D_

Prevent textbox autofill with previously entered values

This is the answer.

_x000D_
_x000D_
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
_x000D_
_x000D_

AutoCompleteType="Disabled"

If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go

'Options' --> 'Security'(tab) --> Untick

'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.

This should solve the problem

Getting rid of all the rounded corners in Twitter Bootstrap

There is a very easy way to customize Bootstrap:

  1. Just go to http://getbootstrap.com/customize/
  2. Find all "radius" and modify them as you wish.
  3. Click "Compile and Download" and enjoy your own version of Bootstrap.

Why am I getting the error "connection refused" in Python? (Sockets)

in your server.py file make : host ='192.168.1.94' instead of host = socket.gethostname()

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

What is a Y-combinator?

I've lifted this from http://www.mail-archive.com/[email protected]/msg02716.html which is an explanation I wrote several years ago.

I'll use JavaScript in this example, but many other languages will work as well.

Our goal is to be able to write a recursive function of 1 variable using only functions of 1 variables and no assignments, defining things by name, etc. (Why this is our goal is another question, let's just take this as the challenge that we're given.) Seems impossible, huh? As an example, let's implement factorial.

Well step 1 is to say that we could do this easily if we cheated a little. Using functions of 2 variables and assignment we can at least avoid having to use assignment to set up the recursion.

// Here's the function that we want to recurse.
X = function (recurse, n) {
  if (0 == n)
    return 1;
  else
    return n * recurse(recurse, n - 1);
};

// This will get X to recurse.
Y = function (builder, n) {
  return builder(builder, n);
};

// Here it is in action.
Y(
  X,
  5
);

Now let's see if we can cheat less. Well firstly we're using assignment, but we don't need to. We can just write X and Y inline.

// No assignment this time.
function (builder, n) {
  return builder(builder, n);
}(
  function (recurse, n) {
    if (0 == n)
      return 1;
    else
      return n * recurse(recurse, n - 1);
  },
  5
);

But we're using functions of 2 variables to get a function of 1 variable. Can we fix that? Well a smart guy by the name of Haskell Curry has a neat trick, if you have good higher order functions then you only need functions of 1 variable. The proof is that you can get from functions of 2 (or more in the general case) variables to 1 variable with a purely mechanical text transformation like this:

// Original
F = function (i, j) {
  ...
};
F(i,j);

// Transformed
F = function (i) { return function (j) {
  ...
}};
F(i)(j);

where ... remains exactly the same. (This trick is called "currying" after its inventor. The language Haskell is also named for Haskell Curry. File that under useless trivia.) Now just apply this transformation everywhere and we get our final version.

// The dreaded Y-combinator in action!
function (builder) { return function (n) {
  return builder(builder)(n);
}}(
  function (recurse) { return function (n) {
    if (0 == n)
      return 1;
    else
      return n * recurse(recurse)(n - 1);
  }})(
  5
);

Feel free to try it. alert() that return, tie it to a button, whatever. That code calculates factorials, recursively, without using assignment, declarations, or functions of 2 variables. (But trying to trace how it works is likely to make your head spin. And handing it, without the derivation, just slightly reformatted will result in code that is sure to baffle and confuse.)

You can replace the 4 lines that recursively define factorial with any other recursive function that you want.

how to pass list as parameter in function

public void SomeMethod(List<DateTime> dates)
{
    // do something
}

How to deselect all selected rows in a DataGridView control?

To deselect all rows and cells in a DataGridView, you can use the ClearSelection method:

myDataGridView.ClearSelection()

If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again:

myDataGridView.CurrentCell = Nothing

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example:

Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub

Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing.

(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

What is the behavior difference between return-path, reply-to and from?

for those who got here because the title of the question:

I use Reply-To: address with webforms. when someone fills out the form, the webpage sends an automatic email to the page's owner. the From: is the automatic mail sender's address, so the owner knows it is from the webform. but the Reply-To: address is the one filled in in the form by the user, so the owner can just hit reply to contact them.

How do I get the full url of the page I am on in C#

Request.Url.AbsoluteUri

This property does everything you need, all in one succinct call.

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

JavaScript moving element in the DOM

Sorry for bumping this thread I stumbled over the "swap DOM-elements" problem and played around a bit

The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)

The Code:

$('#element1').insertAfter($('#element2'));

The jQuery documentation says that insertAfter() moves the element and doesn't clone it

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

2019 June answer

Great news! It seems that the @angular/cdk package now has first-class support for portals!

As of the time of writing, I didn't find the above official docs particularly helpful (particularly with regard to sending data into and receiving events from the dynamic components). In summary, you will need to:

Step 1) Update your AppModule

Import PortalModule from the @angular/cdk/portal package and register your dynamic component(s) inside entryComponents

@NgModule({
  declarations: [ ..., AppComponent, MyDynamicComponent, ... ]
  imports:      [ ..., PortalModule, ... ],
  entryComponents: [ ..., MyDynamicComponent, ... ]
})
export class AppModule { }

Step 2. Option A: If you do NOT need to pass data into and receive events from your dynamic components:

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onClickAddChild()">Click to add child component</button>
    <ng-template [cdkPortalOutlet]="myPortal"></ng-template>
  `
})
export class AppComponent  {
  myPortal: ComponentPortal<any>;
  onClickAddChild() {
    this.myPortal = new ComponentPortal(MyDynamicComponent);
  }
}

@Component({
  selector: 'app-child',
  template: `<p>I am a child.</p>`
})
export class MyDynamicComponent{
}

See it in action

Step 2. Option B: If you DO need to pass data into and receive events from your dynamic components:

// A bit of boilerplate here. Recommend putting this function in a utils 
// file in order to keep your component code a little cleaner.
function createDomPortalHost(elRef: ElementRef, injector: Injector) {
  return new DomPortalHost(
    elRef.nativeElement,
    injector.get(ComponentFactoryResolver),
    injector.get(ApplicationRef),
    injector
  );
}

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onClickAddChild()">Click to add random child component</button>
    <div #portalHost></div>
  `
})
export class AppComponent {

  portalHost: DomPortalHost;
  @ViewChild('portalHost') elRef: ElementRef;

  constructor(readonly injector: Injector) {
  }

  ngOnInit() {
    this.portalHost = createDomPortalHost(this.elRef, this.injector);
  }

  onClickAddChild() {
    const myPortal = new ComponentPortal(MyDynamicComponent);
    const componentRef = this.portalHost.attach(myPortal);
    setTimeout(() => componentRef.instance.myInput 
      = '> This is data passed from AppComponent <', 1000);
    // ... if we had an output called 'myOutput' in a child component, 
    // this is how we would receive events...
    // this.componentRef.instance.myOutput.subscribe(() => ...);
  }
}

@Component({
  selector: 'app-child',
  template: `<p>I am a child. <strong>{{myInput}}</strong></p>`
})
export class MyDynamicComponent {
  @Input() myInput = '';
}

See it in action

Change background colour for Visual Studio

You can also use the Visual Studio Theme Generator. I have only tried this with VS 2005, but the settings it generates may work with newer versions of VS as well.

In case the link goes dead in the future here is a dark theme I generated. Just put this text into a file named VS_2005_dark_theme.vssettings and import it using Tools -> Import and Export Settings:

<UserSettings>
    <ApplicationIdentity version="8.0"/>
    <ToolsOptions>
        <ToolsOptionsCategory name="Environment" RegisteredName="Environment"/>
    </ToolsOptions>
    <Category name="Environment_Group" RegisteredName="Environment_Group">
        <Category name="Environment_FontsAndColors" Category="{1EDA5DD4-927A-43a7-810E-7FD247D0DA1D}" Package="{DA9FB551-C724-11d0-AE1F-00A0C90FFFC3}" RegisteredName="Environment_FontsAndColors" PackageName="Visual Studio Environment Package">
            <PropertyValue name="Version">2</PropertyValue>
            <FontsAndColors Version="2.0">
                <Categories>
                    <Category GUID="{5C48B2CB-0366-4FBF-9786-0BB37E945687}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0000FF00" Background="0x00003700" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{9973EFDF-317D-431C-8BC1-5E88CBFD4F7F}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0057C732" Background="0x0017340E" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0}" FontName="Monaco" FontSize="9" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="00CFCFCF" Background="00383838" BoldFont="No"/>
                            <Item Name="Indicator Margin" Foreground="0x02000000" Background="00383838" BoldFont="No"/>
                            <Item Name="Line Numbers" Foreground="00828282" Background="00383838" BoldFont="No"/>
                            <Item Name="Visible White Space" Foreground="0x00808080" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Compiler Error" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Value" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Selector" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS String Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Element Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Identifier" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Number" Foreground="002FFE60" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Preprocessor Keyword" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Stale Code" Foreground="0x00808080" Background="0x00C0C0C0" BoldFont="No"/>
                            <Item Name="String" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="String (C# Verbatim)" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Task List Shortcut" Foreground="0x00FFFFFF" Background="0x02C0C0C0" BoldFont="No"/>
                            <Item Name="User Keywords" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="User Types" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Warning" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Class" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Name" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Value" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Processing Instruction" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>                            
                            <Item Name="XML @ Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Attribute" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Tag" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Processing Instruction" Foreground="0x0015496C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XSLT Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>                                                                 
                        </Items>
                    </Category>
                </Categories>
            </FontsAndColors>
        </Category>
    </Category>
</UserSettings>

What is the difference between angular-route and angular-ui-router?

ui router make your life easier! You can add it to you AngularJS application via injecting it into your applications...

ng-route comes as part of the core AngularJS, so it's simpler and gives you fewer options...

Look at here to understand ng-route better: https://docs.angularjs.org/api/ngRoute

Also when using it, don't forget to use: ngView ..

ng-ui-router is different but:

https://github.com/angular-ui/ui-router but gives you more options....

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

How to Change color of Button in Android when Clicked?

Try This

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                button.setBackgroundColor(Color.RED);
            } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button.setBackgroundColor(Color.BLUE);
            }
            return false;
        }

    });

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

My simple solution:

$("form").children('input[type="submit"]').click();

It is work for me.

How to check if another instance of my shell script is running

Someone please shoot me down if I'm wrong here

I understand that the mkdir operation is atomic, so you could create a lock directory

#!/bin/sh
lockdir=/tmp/AXgqg0lsoeykp9L9NZjIuaqvu7ANILL4foeqzpJcTs3YkwtiJ0
mkdir $lockdir  || {
    echo "lock directory exists. exiting"
    exit 1
}
# take pains to remove lock directory when script terminates
trap "rmdir $lockdir" EXIT INT KILL TERM

# rest of script here

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

adding noise to a signal in python

For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:

import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with 
# clean_signal = pd.read_csv("your_data.csv")   
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float) 
print(clean_signal)
"""
print output: 
    A    B
0  1.0  2.0
1  3.0  4.0
"""
import numpy as np 
mu, sigma = 0, 0.1 
# creating a noise with the same dimension as the dataset (2,2) 
noise = np.random.normal(mu, sigma, [2,2]) 
print(noise)

"""
print output: 
array([[-0.11114313,  0.25927152],
       [ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output: 
          A         B
0  0.888857  2.259272
1  3.067015  3.906358
""" 

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

tl;dr

Instant.now()
       .toString()

2016-05-06T23:24:25.694Z

ZonedDateTime
.now
( 
    ZoneId.of( "America/Montreal" ) 
)
.format(  DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )

2016-05-06 19:24:25.694

java.time

In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.

If you want to eliminate any microseconds or nanoseconds from your data, truncate.

Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;

The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.

An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.

Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();

2016-05-06T23:24:25.694Z

Replace the T in the middle with a space, and the Z with nothing, to get your desired output.

String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.

2016-05-06 23:24:25.694

As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.

String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );

Joda-Time

The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.

The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.

System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );

When run…

Now: 2013-11-26T20:25:12.014Z

Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:

int millisOfSecond = myDateTime.getMillisOfSecond ();

How do I delete an exported environment variable?

unset is the command you're looking for.

unset GNUPLOT_DRIVER_DIR

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!

To view an image in the browser, you can visit the link data:image/png;base64,**image data here** for a base64-encoded PNG image, or data:image/jpg;base64,**image data here** for a base64-encoded JPG image. An example link can be found at the end of this answer.

To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**). Now your image is 100% embedded into your Jupyter Notebook file!

Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==

Example markdown: ![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

ToggleClass animate jQuery?

You should look at the toggle function found on jQuery. This will allow you to specify an easing method to define how the toggle works.

slideToggle will only slide up and down, not left/right if that's what you are looking for.

If you need the class to be toggled as well you can deifine that in the toggle function with a:

$(this).closest('article').toggle('slow', function() {
    $(this).toggleClass('expanded');
});

Is there a "previous sibling" selector?

There is no official way to do that at the moment but you can use a little trick to achieve this ! Remember that it is experimental and it has some limitation ... (check this link if you worries about navigator compatibility )

What you can do is use a CSS3 selector : the pseudo classe called nth-child()

_x000D_
_x000D_
#list>* {_x000D_
  display: inline-block;_x000D_
  padding: 20px 28px;_x000D_
  margin-right: 5px;_x000D_
  border: 1px solid #bbb;_x000D_
  background: #ddd;_x000D_
  color: #444;_x000D_
  margin: 0.4em 0;_x000D_
}_x000D_
_x000D_
#list :nth-child(-n+4) {_x000D_
  color: #600b90;_x000D_
  border: 1px dashed red;_x000D_
  background: orange;_x000D_
}
_x000D_
<p>The oranges elements are the previous sibling li selected using li:nth-child(-n+4)</p>_x000D_
_x000D_
<div id="list">_x000D_
  <span>1</span><!-- this will be selected -->_x000D_
  <p>2</p><!-- this will be selected -->_x000D_
  <p>3</p><!-- this will be selected -->_x000D_
  <div>4</div><!-- this will be selected -->_x000D_
  <div>5</div>_x000D_
  <p>6</p>_x000D_
  <p>7</p>_x000D_
  <p>8</p>_x000D_
  <p>9</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Limitations

  • You can't select previous elements based on the classes of the next elements
  • This is the same for pseudo classes

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

You are off slightly on a few things here, so hopefully the following helps.

Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.

It's also good practice to use Option Explicit at the top of your modules to force variable declaration.

The following will do what you are after:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

If you do want to manipulate the values within the array then do this:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Pass variables by reference in JavaScript

Simple Object

_x000D_
_x000D_
function foo(x) {
  // Function with other context
  // Modify `x` property, increasing the value
  x.value++;
}

// Initialize `ref` as object
var ref = {
  // The `value` is inside `ref` variable object
  // The initial value is `1`
  value: 1
};

// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);

console.log(ref.value); // Prints "3"
_x000D_
_x000D_
_x000D_


Custom Object

Object rvar

_x000D_
_x000D_
/**
 * Aux function to create by-references variables
 */
function rvar(name, value, context) {
  // If `this` is a `rvar` instance
  if (this instanceof rvar) {
    // Inside `rvar` context...
    
    // Internal object value
    this.value = value;
    
    // Object `name` property
    Object.defineProperty(this, 'name', { value: name });
    
    // Object `hasValue` property
    Object.defineProperty(this, 'hasValue', {
      get: function () {
        // If the internal object value is not `undefined`
        return this.value !== undefined;
      }
    });
    
    // Copy value constructor for type-check
    if ((value !== undefined) && (value !== null)) {
      this.constructor = value.constructor;
    }
    
    // To String method
    this.toString = function () {
      // Convert the internal value to string
      return this.value + '';
    };
  } else {
    // Outside `rvar` context...
    
    // Initialice `rvar` object
    if (!rvar.refs) {
      rvar.refs = {};
    }
    
    // Initialize context if it is not defined
    if (!context) {
      context = window;
    }
    
    // Store variable
    rvar.refs[name] = new rvar(name, value, context);
    
    // Define variable at context
    Object.defineProperty(context, name, {
      // Getter
      get: function () { return rvar.refs[name]; },
      // Setter
      set: function (v) { rvar.refs[name].value = v; },
      // Can be overrided?
      configurable: true
    });

    // Return object reference
    return context[name];
  }
}

// Variable Declaration

  // Declare `test_ref` variable
  rvar('test_ref_1');

  // Assign value `5`
  test_ref_1 = 5;
  // Or
  test_ref_1.value = 5;

  // Or declare and initialize with `5`:
  rvar('test_ref_2', 5);

// ------------------------------
// Test Code

// Test Function
function Fn1 (v) { v.value = 100; }

// Declare
rvar('test_ref_number');

// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);

// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);

// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);

// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);

// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');

// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');

// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true

// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true

// Increase value
test_ref_number++;
test_ref_number.value === 101; // true

// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true

test_ref_str.value === "a"; // true

// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true 
_x000D_
_x000D_
_x000D_

Set Text property of asp:label in Javascript PROPER way

Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.

So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)

How to set margin of ImageView using code, not xml

For me this worked:

int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());

MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);

How to change Android usb connect mode to charge only?

To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.

react-router (v4) how to go back?

I am not sure if anyone else ran into this problem or may need to see this. But I spent about 3 hours trying to solve this issue:

I wanted to implement a simple goBack() on the click of a button. I thought I was off to a good start because my App.js was already wrapped in the Router and I was importing { BrowserRouter as Router } from 'react-router-dom'; ... Since the Router element allows me to assess the history object.

ex:

import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
  return (
    <Router>
      <Header />
      <Route path='/' component={Splash} exact />
      <Route path='/home' component={Info} exact />
      <Route path='/timer' component={Timer} exact />
      <Route path='/options' component={Options} exact />
      <Footer />
    </Router>
  );
}
export default App;

BUT the trouble was on my Nav (a child component) module, I had to 'import { withRouter } from 'react-router-dom';' and then force an export with:

export default withRouter(Nav);

ex:

import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
    render() {
        return (
            <div>
                <label htmlFor='back'></label>
                <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                <label htmlFor='logOut'></label>
                <button id='logOut' ><a href='./'>Log-Out</a>            
</button>
            </div>
        );
    }
}
export default withRouter(Nav);

in summary, withRouter was created because of a known issue in React where in certain scenarios when inheritance from a router is refused, a forced export is necessary.

How can I capture the result of var_dump to a string?

If you want to have a look at a variable's contents during runtime, consider using a real debugger like XDebug. That way you don't need to mess up your source code, and you can use a debugger even while normal users visit your application. They won't notice.

no sqljdbc_auth in java.library.path

I've just encountered the same problem but within my own application. I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.

Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll to path.. which is easy to say:

PathHelper.appendToPath("C:\\sqljdbc_6.2\\enu\\auth\\x64");

once you know how to do it:

import java.lang.reflect.Field;

public class PathHelper {
    public static void appendToPath(String dir){

        String path = System.getProperty("java.library.path");
        path = dir + ";" + path;
        System.setProperty("java.library.path", path);

        try {

            final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
            sysPathsField.setAccessible(true);
            sysPathsField.set(null, null);

        }
        catch (Exception ex){
            throw new RuntimeException(ex);
        }

    }

}

Now integration authentication works like a charm :).

Credits to https://stackoverflow.com/a/21730111/1734640 for letting me figure this out.

What datatype should be used for storing phone numbers in SQL Server 2005?

Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.

Looping through JSON with node.js

If you want to avoid blocking, which is only necessary for very large loops, then wrap the contents of your loop in a function called like this: process.nextTick(function(){<contents of loop>}), which will defer execution until the next tick, giving an opportunity for pending calls from other asynchronous functions to be processed.

How to get all properties values of a JavaScript Object (without knowing the keys)?

Apparently - as I recently learned - this is the fastest way to do it:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

What do these three dots in React do?

It is called spreads syntax in javascript.

It use for destructuring an array or object in javascript.

example:

const objA = { a: 1, b: 2, c: 3 }
const objB = { ...objA, d: 1 }
/* result of objB will be { a: 1, b: 2, c: 3, d: 1 } */
console.log(objB)

const objC = { ....objA, a: 3 }
/* result of objC will be { a: 3, b: 2, c: 3, d: 1 } */
console.log(objC)

You can do it same result with Object.assign() function in javascript.

Reference:Spread syntax

Check that Field Exists with MongoDB

db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })

How to check which version of Keras is installed?

Simple command to check keras version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit) 

>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'

Do copyright dates need to be updated?

It is important to recognize that the copyright laws have changed and that for non-US sources, especially after the USA joining the Berne Convention on March 1, 1989, copyright registration in not necessary for enforcement of a copyright notice.
Here is a resumé quoted from the Cornell University Law School (copied on March 4, 2015 from https://www.law.cornell.edu/wex/copyright:

"Copyright copyright: an overview

The U.S. Copyright Act, 17 U.S.C. §§ 101 - 810, is Federal legislation enacted by Congress under its Constitutional grant of authority to protect the writings of authors. See U.S. Constitution, Article I, Section 8. Changing technology has led to an ever expanding understanding of the word "writings." The Copyright Act now reaches architectural design, software, the graphic arts, motion pictures, and sound recordings. See § 106. As of January 1, 1978, all works of authorship fixed in a tangible medium of expression and within the subject matter of copyright were deemed to fall within the exclusive jurisdiction of the Copyright Act regardless of whether the work was created before or after that date and whether published or unpublished. See § 301. See also preemption.

The owner of a copyright has the exclusive right to reproduce, distribute, perform, display, license, and to prepare derivative works based on the copyrighted work. See § 106. The exclusive rights of the copyright owner are subject to limitation by the doctrine of "fair use." See § 107. Fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching, scholarship, or research is not copyright infringement. To determine whether or not a particular use qualifies as fair use, courts apply a multi-factor balancing test. See § 107.

Copyright protection subsists in original works of authorship fixed in any tangible medium of expression from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device. See § 102. Copyright protection does not extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery. For example, if a book is written describing a new system of bookkeeping, copyright protection only extends to the author's description of the bookkeeping system; it does not protect the system itself. See Baker v. Selden, 101 U.S. 99 (1879).

According to the Copyright Act of 1976, registration of copyright is voluntary and may take place at any time during the term of protection. See § 408. Although registration of a work with the Copyright Office is not a precondition for protection, an action for copyright infringement may not be commenced until the copyright has been formally registered with the Copyright Office. See § 411.

Deposit of copies with the Copyright Office for use by the Library of Congress is a separate requirement from registration. Failure to comply with the deposit requirement within three months of publication of the protected work may result in a civil fine. See § 407. The Register of Copyrights may exempt certain categories of material from the deposit requirement.

In 1989 the U.S. joined the Berne Convention for the Protection of Literary and Artistic Works. In accordance with the requirements of the Berne Convention, notice is no longer a condition of protection for works published after March 1, 1989. This change to the notice requirement applies only prospectively to copies of works publicly distributed after March 1, 1989.

The Berne Convention also modified the rule making copyright registration a precondition to commencing a lawsuit for infringement. For works originating from a Berne Convention country, an infringement action may be initiated without registering the work with the U.S. Copyright Office. However, for works of U.S. origin, registration prior to filing suit is still required.

The federal agency charged with administering the act is the Copyright Office of the Library of Congress. See § 701 of the act. Its regulations are found in Parts 201 - 204 of title 37 of the Code of Federal Regulations."

Python and pip, list all versions of a package that's available?

I didn't have any luck with yolk, yolk3k or pip install -v but so I ended up using this (adapted to Python 3 from eric chiang's answer):

import json
import requests
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.python.org/pypi/{}/json".format(package_name)
    data = requests.get(url).json()
    return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)

>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

Setting core.filemode to false does work, but make sure the settings in ~/.gitconfig aren't being overridden by those in .git/config.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

ASP.NET Button to redirect to another page

You can use PostBackUrl="~/Confirm.aspx"

For example:

In your .aspx file

<asp:Button ID="btnConfirm" runat="server" Text="Confirm" PostBackUrl="~/Confirm.aspx" />

or in your .cs file

btnConfirm.PostBackUrl="~/Confirm.aspx"

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

Define static method in source-file with declaration in header-file in C++

Keywords static and virtual should not be repeated in the definition. They should only be used in the class declaration.

How to hide columns in an ASP.NET GridView with auto-generated columns?

As said by others, RowDataBound or RowCreated event should work but if you want to avoid events declaration and put the whole code just below DataBind function call, you can do the following:

GridView1.DataBind()
If GridView1.Rows.Count > 0 Then
    GridView1.HeaderRow.Cells(0).Visible = False
    For i As Integer = 0 To GridView1.Rows.Count - 1
        GridView1.Rows(i).Cells(0).Visible = False
    Next
End If

Newline character in StringBuilder

Just create an extension for the StringBuilder class:

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module

How do I share a global variable between c files?

Use extern keyword in another .c file.

Calculate text width with JavaScript

Try this code:

function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto"; 
obj.style.height = "auto"; 
var Ret = obj.getBoundingClientRect(); 
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px"; 
return Ret;
}

sql searching multiple words in a string

if you put all the searched words in a temporaray table say @tmp and column col1, then you could try this:

Select * from T where C like (Select '%'+col1+'%' from @temp);

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

Why when I transfer a file through SFTP, it takes longer than FTP?

Encryption has not only cpu, but also some network overhead.

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

What are some reasons for jquery .focus() not working?

Don't forget that an input field must be visible first, thereafter you're able to focus it.

$("#elementid").show();
$("#elementid input[type=text]").focus();

The apk must be signed with the same certificates as the previous version

You can use new feature Google play app signing to generate a new key file .

After May 2017 Google play store add a new feature on Play store and It’s Good News For Android Developers. From this feature, Developer can update their app or Apk who lost a KeyStore file. you need to enable google play app signing on play store console.

https://support.google.com/googleplay/android-developer/answer/7384423?hl=en

http://www.geekcodehub.com/2018/05/23/keystore-lost-in-android/

Maximum request length exceeded.

There's an element in web.config to configure the max size of the uploaded file:

<httpRuntime 
    maxRequestLength="1048576"
  />

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

Remove a git commit which has not been pushed

Actually, when you use git reset, you should refer to the commit that you are resetting to; so you would want the db0c078 commit, probably.

An easier version would be git reset --hard HEAD^, to reset to the previous commit before the current head; that way you don't have to be copying around commit IDs.

Beware when you do any git reset --hard, as you can lose any uncommitted changes you have. You might want to check git status to make sure your working copy is clean, or that you do want to blow away any changes that are there.

In addition, instead of HEAD you can use origin/master as reference, as suggested by @bdonlan in the comments: git reset --hard origin/master

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

bad operand types for binary operator "&" java

Because & has a lesser priority than ==.

Your code is equivalent to a[0] & (1 == 0), and unless a[0] is a boolean this won't compile...

You need to:

(a[0] & 1) == 0

etc etc.

(yes, Java does hava a boolean & operator -- a non shortcut logical and)

Uncaught ReferenceError: $ is not defined error in jQuery

Scripts are loaded in the order you have defined them in the HTML.

Therefore if you first load:

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

without loading jQuery first, then $ is not defined.

You need to first load jQuery so that you can use it.

I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

How to create a remote Git repository from a local one?

I think you make a bare repository on the remote side, git init --bare, add the remote side as the push/pull tracker for your local repository (git remote add origin URL), and then locally you just say git push origin master. Now any other repository can pull from the remote repository.

SQLAlchemy: What's the difference between flush() and commit()?

As @snapshoe says

flush() sends your SQL statements to the database

commit() commits the transaction.

When session.autocommit == False:

commit() will call flush() if you set autoflush == True.

When session.autocommit == True:

You can't call commit() if you haven't started a transaction (which you probably haven't since you would probably only use this mode to avoid manually managing transactions).

In this mode, you must call flush() to save your ORM changes. The flush effectively also commits your data.

Remove an item from an IEnumerable<T> collection

The IEnumerable interface is just that, enumerable - it doesn't provide any methods to Add or Remove or modify the list at all.

The interface just provides a way to iterate over some items - most implementations that require enumeration will implement IEnumerable such as List<T>

Why don't you just use your code without the implicit cast to IEnumerable

// Treat this like a list, not an enumerable
List<User> modifiedUsers = new List<User>();

foreach(var u in users)
{
   if(u.userId != 1233)
   {
        // Use List<T>.Add
        modifiedUsers.Add(u);
   }
}

How do I get a TextBox to only accept numeric input in WPF?

In Windows Forms it was easy; you can add an event for KeyPress and everything works easily. However, in WPF that event isn't there. But there is a much easier way for it.

The WPF TextBox has the TextChanged event which is general for everything. It includes pasting, typing and whatever that can come up to your mind.

So you can do something like this:

XAML:

<TextBox name="txtBox1" ... TextChanged="TextBox_TextChanged"/>

CODE BEHIND:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
    string s = Regex.Replace(((TextBox)sender).Text, @"[^\d.]", "");
    ((TextBox)sender).Text = s;
}

This also accepts . , if you don't want it, just remove it from the regex statement to be @[^\d].

Note: This event can be used on many TextBox'es as it uses the sender object's Text. You only write the event once and can use it for multiple TextBox'es.

Web scraping with Python

Python has good options to scrape the web. The best one with a framework is scrapy. It can be a little tricky for beginners, so here is a little help.
1. Install python above 3.5 (lower ones till 2.7 will work).
2. Create a environment in conda ( I did this).
3. Install scrapy at a location and run in from there.
4. Scrapy shell will give you an interactive interface to test you code.
5. Scrapy startproject projectname will create a framework.
6. Scrapy genspider spidername will create a spider. You can create as many spiders as you want. While doing this make sure you are inside the project directory.


The easier one is to use requests and beautiful soup. Before starting give one hour of time to go through the documentation, it will solve most of your doubts. BS4 offer wide range of parsers that you can opt for. Use user-agent and sleep to make scraping easier. BS4 returns a bs.tag so use variable[0]. If there is js running, you wont be able to scrape using requests and bs4 directly. You could get the api link then parse the JSON to get the information you need or try selenium.

Convert interface{} to int

Instead of

iAreaId := int(val)

you want a type assertion:

iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version 

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

...

A non-constant value x can be converted to type T in any of these cases:

  1. x is assignable to T.
  2. x's type and T have identical underlying types.
  3. x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  4. x's type and T are both integer or floating point types.
  5. x's type and T are both complex types.
  6. x is an integer or a slice of bytes or runes and T is a string type.
  7. x is a string and T is a slice of bytes or runes.

But

iAreaId := int(val)

is not any of the cases 1.-7.

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

DataTable: Hide the Show Entries dropdown but keep the Search box

sDom: "Tfrtip" or via a callback:

"fnHeaderCallback": function(){
    $('#YOURTABLENAME-table_length').hide();
}

What is an unsigned char?

In C++, there are three distinct character types:

  • char
  • signed char
  • unsigned char

If you are using character types for text, use the unqualified char:

  • it is the type of character literals like 'a' or '0'.
  • it is the type that makes up C strings like "abcde"

It also works out as a number value, but it is unspecified whether that value is treated as signed or unsigned. Beware character comparisons through inequalities - although if you limit yourself to ASCII (0-127) you're just about safe.

If you are using character types as numbers, use:

  • signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)
  • unsigned char, which gives you at least the 0 to 255 range.

"At least", because the C++ standard only gives the minimum range of values that each numeric type is required to cover. sizeof (char) is required to be 1 (i.e. one byte), but a byte could in theory be for example 32 bits. sizeof would still be report its size as 1 - meaning that you could have sizeof (char) == sizeof (long) == 1.

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

Why should Java 8's Optional not be used in arguments

I think that is because you usually write your functions to manipulate data, and then lift it to Optional using map and similar functions. This adds the default Optional behavior to it. Of course, there might be cases, when it is necessary to write your own auxilary function that works on Optional.

jquery to change style attribute of a div class

$('.handle').css('left','300px') try this, identificator first then the value

more on this here:

http://api.jquery.com/css/

How do I fix the npm UNMET PEER DEPENDENCY warning?

In my case all the dependencies were already there. Please update NPM in that case as it might have been crashed. It solved my problem.

npm install -g npm

Get Insert Statement for existing row in MySQL

Within MySQL work bench perform the following:

  1. Click Server > Data Export

  2. In the Object Selection Tab select the desired schema.

  3. Next, select the desired tables using the list box to the right of the schema.

  4. Select a file location to export the script.

  5. Click Finish.

  6. Navigate to the newly created file and copy the insert statements.

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

HTML button onclick event

This example will help you:

<form>
    <input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>

You can open next page on same page by:

<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">

Populate data table from data reader

As Sagi stated in their answer DataTable.Load is a good solution. If you are trying to load multiple tables from a single reader you do not need to call DataReader.NextResult. The DataTable.Load method also advances the reader to the next result set (if any).

// Read every result set in the data reader.
while (!reader.IsClosed)
{
    DataTable dt = new DataTable();
    // DataTable.Load automatically advances the reader to the next result set
    dt.Load(reader);
    items.Add(dt);
}

What is the difference between Swing and AWT?

  • swing component provide much flexible user interface because it follow model view controller(mvc).
  • awt is not mvc based.
  • swing works faster.
  • awt does not work faster.
  • swing components are light weight.
  • awt components are heavy weight.
  • swing occupies less memory space.
  • awt occupies more memory space.
  • swing component is platform independent.
  • awt is platform dependent.
  • swing require javax.swing package.
  • awt require javax.awt package.

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Java JTable setting Column Width

Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.

TableColumn column = null;
for (int i = 0; i < 3; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 0) 
        column.setMaxWidth(10);
    if (i == 2)
        column.setMaxWidth(50);
}

How to change button text or link text in JavaScript?

Change .text to .textContent to get/set the text content.

Or since you're dealing with a single text node, use .firstChild.data in the same manner.

Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.

function toggleText(button_id) 
{
   var el = document.getElementById(button_id);
   if (el.firstChild.data == "Lock") 
   {
       el.firstChild.data = "Unlock";
   }
   else 
   {
     el.firstChild.data = "Lock";
   }
}

Or even more compact like this:

function toggleText(button_id)  {
   var text = document.getElementById(button_id).firstChild;
   text.data = text.data == "Lock" ? "Unlock" : "Lock";
}

Get child Node of another Node, given node name

If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

Query grants for a table in postgres

Adding on to @shruti's answer

To query grants for all tables in a schema for a given user

select a.tablename, 
       b.usename, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'select') as select,
       HAS_TABLE_PRIVILEGE(usename,tablename, 'insert') as insert, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'update') as update, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'delete') as delete, 
       HAS_TABLE_PRIVILEGE(usename,tablename, 'references') as references 
from pg_tables a, 
     pg_user b 
where schemaname='your_schema_name' 
      and b.usename='your_user_name' 
order by tablename;

Passing arguments to "make run"

I don't know a way to do what you want exactly, but a workaround might be:

run: ./prog
    ./prog $(ARGS)

Then:

make ARGS="asdf" run
# or
make run ARGS="asdf"

Change Background color (css property) using Jquery

Change Background Color using on click button jquery

Below is the code of jquery, which you can put in your head tag.

jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").addClass("myclass");
      });
    });
</script>

CSS Code:

<style>
    .myclass {
        background-color: red;
        padding: 100px;
        color: #fff;
    }
</style>

HTML Code:

<body>
    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    <button>Click Here</button>
</body>

MySQL error 1449: The user specified as a definer does not exist

grant all on *.* to 'username'@'%' identified by 'password' with grant option;

example:

grant all on *.* to 'web2vi'@'%' identified by 'password' with grant option;

Delete files older than 3 months old in a directory using .NET

For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour

public static void LimpiarArchivosViejos()
    {
        DayOfWeek today = DateTime.Today.DayOfWeek;
        int hora = DateTime.Now.Hour;
        if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
        {
            CleanPdfOlds();
            CleanExcelsOlds();
        }

    }
    private static void CleanPdfOlds(){
        string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }
    private static void CleanExcelsOlds()
    {
        string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
        foreach (string file in files2)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }

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

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

Extract file name from path, no matter what the os/path format

Here's a regex-only solution, which seems to work with any OS path on any OS.

No other module is needed, and no preprocessing is needed either :

import re

def extract_basename(path):
  """Extracts basename of a given path. Should Work with any OS Path on any OS"""
  basename = re.search(r'[^\\/]+(?=[\\/]?$)', path)
  if basename:
    return basename.group(0)


paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
         'a/b/../../a/b/c/', 'a/b/../../a/b/c']

print([extract_basename(path) for path in paths])
# ['c', 'c', 'c', 'c', 'c', 'c', 'c']


extra_paths = ['C:\\', 'alone', '/a/space in filename', 'C:\\multi\nline']

print([extract_basename(path) for path in extra_paths])
# ['C:', 'alone', 'space in filename', 'multi\nline']

Update:

If you only want a potential filename, if present (i.e., /a/b/ is a dir and so is c:\windows\), change the regex to: r'[^\\/]+(?![\\/])$' . For the "regex challenged," this changes the positive forward lookahead for some sort of slash to a negative forward lookahead, causing pathnames that end with said slash to return nothing instead of the last sub-directory in the pathname. Of course there is no guarantee that the potential filename actually refers to a file and for that os.path.is_dir() or os.path.is_file() would need to be employed.

This will match as follows:

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir()
                    # should be used to tell us for sure

The regex can be tested here.

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

"No resource identifier found for attribute 'showAsAction' in package 'android'"

Add compat library compilation to the build.gradle file:

compile 'com.android.support:appcompat-v7:19.+'

How to create roles in ASP.NET Core and assign them to users?

My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.

You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.

private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles 
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        string[] roleNames = { "Admin", "Manager", "Member" };
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        //Here you could create a super user who will maintain the web app
        var poweruser = new ApplicationUser
        {

            UserName = Configuration["AppSettings:UserName"],
            Email = Configuration["AppSettings:UserEmail"],
        };
    //Ensure you have these values in your appsettings.json file
        string userPWD = Configuration["AppSettings:UserPassword"];
        var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);

       if(_user == null)
       {
            var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
       }
    }

and then you could call the CreateRoles(serviceProvider).Wait(); method from the Configure method in the Startup class. ensure you have IServiceProvider as a parameter in the Configure class.

Using role-based authorization in a controller to filter user access: Question 2

You can do this easily, like so.

[Authorize(Roles="Manager")]
public class ManageController : Controller
{
   //....
}

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will

[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
 .....
 */ 
}

While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here

Removing an activity from the history stack

You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

ORA-30926: unable to get a stable set of rows in the source tables

Had the error today on a 12c and none of the existing answers fit (no duplicates, no non-deterministic expressions in the WHERE clause). My case was related to that other possible cause of the error, according to Oracle's message text (emphasis below):

ORA-30926: unable to get a stable set of rows in the source tables
Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause.

The merge was part of a larger batch, and was executed on a live database with many concurrent users. There was no need to change the statement. I just committed the transaction before the merge, then ran the merge separately, and committed again. So the solution was found in the suggested action of the message:

Action: Remove any non-deterministic where clauses and reissue the dml.

How can I select an element by name with jQuery?

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

How to get a list of all files in Cloud Storage in a Firebase app?

You can use the following code. Here I am uploading the image to firebase storage and then I am storing the image download url to firebase database.

//getting the storage reference
            StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(filePath));

            //adding the file to reference 
            sRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //dismissing the progress dialog
                            progressDialog.dismiss();

                            //displaying success toast 
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();

                            //creating the upload object to store uploaded image details 
                            Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());

                            //adding an upload to firebase database 
                            String uploadId = mDatabase.push().getKey();
                            mDatabase.child(uploadId).setValue(upload);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //displaying the upload progress 
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });

Now to fetch all the images stored in firebase database you can use

//adding an event listener to fetch values
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                //dismissing the progress dialog 
                progressDialog.dismiss();

                //iterating through all the values in database
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Upload upload = postSnapshot.getValue(Upload.class);
                    uploads.add(upload);
                }
                //creating adapter
                adapter = new MyAdapter(getApplicationContext(), uploads);

                //adding adapter to recyclerview
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                progressDialog.dismiss();
            }
        });

Fore more details you can see my post Firebase Storage Example.

How to reset settings in Visual Studio Code?

If you want to reset everything, go to %userprofile%\AppData\Roaming\Code and delete the whole folder after you uninstall the VS code, then install it again.

Also in %userprofile%\.vscode delete extensions folder in case you want to delete all extensions.

JVM heap parameters

I created this toy example in scala, my_file.scala:

object MyObject {

    def main(args: Array[String]) {
        var ab = ArrayBuffer.empty[Int]

        for (i <- 0 to 100 * 1000 * 1000) {
            ab += i
            if (i % 10000 == 0) {
                println("On : %s".format(i))
            }
        }
    }
}

I ran it with:

scala -J-Xms500m -J-Xmx7g my_file.scala

and

scala -J-Xms7g -J-Xmx7g my_file.scala

There are certainly noticeable pauses in -Xms500m version. I am positive that the short pauses are garbage collection runs, and the long ones are heap allocations.

Is there an upside down caret character?

There is no upside down caret character, but you can easily rotate the caret with CSS. This is a simple solution that looks perfect. Press 'Run code snippet' to see it in action:

_x000D_
_x000D_
.upsidedown {_x000D_
transform:rotate(180deg); _x000D_
-webkit-transform:rotate(180deg);_x000D_
-o-transform:rotate(180deg);_x000D_
-ms-transform:rotate(180deg);_x000D_
}_x000D_
.upsidedown.caret {_x000D_
display: inline-block; _x000D_
position:relative; _x000D_
bottom: 0.15em;_x000D_
}
_x000D_
more items <span class="upsidedown caret">^</span>
_x000D_
_x000D_
_x000D_

Please note the following...

  • I did a little correction for the positioning of the caret, as it is normally high (thus low in the rotated version). You want to move it a little up. This 'little' is relative to the font-size, hence the 'em'. Depending on your font choice, you might want to fiddle with this to make it look good.
  • This solution does not work in IE8. You should use a filter if you want IE8 support. IE8 support is not really required nor common in 2018.
  • If you want to use this in combination with Twitter Bootstrap, please rename the class 'caret' to something else, like 'caret_down' (as it collides with a class name from Twitter Bootstrap).

Update built-in vim on Mac OS X

This blog post was helpful for me. I used the "Homebrew built Vim" solution, which in my case saved the new version in /usr/local/bin. At this point, the post suggested hiding the system vim, which didn't work for me, so I used an alias instead.

$ brew install vim
$ alias vim='/path/to/new/vim
$ which vim
vim: aliased to /path/to/new/vim

Build project into a JAR automatically in Eclipse

Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.


Step 1 Create a build.xml file and add to package explorer:

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="." includes="*.class" />
  </target>
</project>

Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml. Build.xml in Eclipse Project

Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.

Ant builder configuration Build step - Targets Tab

Check the Output

The Eclipse output window (named Console) should show the following after a build:

Buildfile: /home/<user>/src/Test/build.xml

CreateJar:
         [jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds

EDIT: Some helpful comments by @yeoman and @betlista

@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion

@betlista I would recomment to not to have build.xml in src folder

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

It is unfortunately easy to program in PHP in a way that consumes memory faster than you realise. Copying strings, arrays and objects instead of using references will do it, though PHP 5 is supposed to do this more automatically than in PHP 4. But dealing with your data set in entirety over several steps is also wasteful compared to processing the smallest logical unit at a time. The classic example is working with large resultsets from a database: most programmers fetch the entire resultset into an array and then loop over it one or more times with foreach(). It is much more memory efficient to use a while() loop to fetch and process one row at a time. The same thing applies to processing a file.

base64 encode in MySQL

Looks like no, though it was requested, and there’s a UDF for it.

Edit: Or there’s… this. Ugh.

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

Disable form auto submit on button click

<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

HTTP GET Request in Node.js Express

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

How to restart adb from root to user mode?

This is a very common issue.

One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.

Just go to Window Task Manager to kill adb process and restart Eclipse.

Will work perfect :)

Chaining multiple filter() in Django, is this a bug?

The way I understand it is that they are subtly different by design (and I am certainly open for correction): filter(A, B) will first filter according to A and then subfilter according to B, while filter(A).filter(B) will return a row that matches A 'and' a potentially different row that matches B.

Look at the example here:

https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

particularly:

Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects

...

In this second example (filter(A).filter(B)), the first filter restricted the queryset to (A). The second filter restricted the set of blogs further to those that are also (B). The entries select by the second filter may or may not be the same as the entries in the first filter.`

JQuery string contains check

Please try:

str1.contains(str2)

Emulating a do-while loop in Bash

Place the body of your loop after the while and before the test. The actual body of the while loop should be a no-op.

while 
    check_if_file_present
    #do other stuff
    (( current_time <= cutoff ))
do
    :
done

Instead of the colon, you can use continue if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5. Or print delimiters between values:

i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'

I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <= are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.

How to plot two histograms together in R?

That image you linked to was for density curves, not histograms.

If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

So, let's start with something like what you have, two separate sets of data and combine them.

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

After that, which is unnecessary if your data is in long format already, you only need one line to make your plot.

ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

enter image description here

Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

enter image description here

How create a new deep copy (clone) of a List<T>?

I'm disappointed Microsoft didn't offer a neat, fast and easy solution like Ruby are doing with the clone() method.

Except that does not create a deep copy, it creates a shallow copy.

With deep copying, you have to be always careful, what exactly do you want to copy. Some examples of possible issues are:

  1. Cycle in the object graph. For example, Book has an Author and Author has a list of his Books.
  2. Reference to some external object. For example, an object could contain open Stream that writes to a file.
  3. Events. If an object contains an event, pretty much anyone could be subscribed to it. This can get especially problematic if the subscriber is something like a GUI Window.

Now, there are basically two ways how to clone something:

  1. Implement a Clone() method in each class that you need cloned. (There is also ICloneable interface, but you should not use that; using a custom ICloneable<T> interface as Trevor suggested is okay.) If you know that all you need is to create a shallow copy of each field of this class, you could use MemberwiseClone() to implement it. As an alternative, you could create a “copy constructor”: public Book(Book original).
  2. Use serialization to serialize your objects into a MemoryStream and then deserialize them back. This requires you to mark each class as [Serializable] and it can also be configured what exactly (and how) should be serialized. But this is more of a “quick and dirty” solution, and will most likely also be less performant.

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

How to Allow Remote Access to PostgreSQL database

In addition to above answers suggesting (1) the modification of the configuration files pg_hba.conf and (2) postgresql.conf and (3) restarting the PostgreSQL service, some Windows computers might also require incoming TCP traffic to be allowed on the port (usually 5432).

To do this, you would need to open Windows Firewall and add an inbound rule for the port (e.g. 5432).

Head to Control Panel\System and Security\Windows Defender Firewall > Advanced Settings > Actions (right tab) > Inbound Rules > New Rule… > Port > Specific local ports and type in the port your using, usually 5432 > (defaults settings for the rest and type any name you'd like)

Windows firewall settings

Now, try connecting again from pgAdmin on the client computer. Restarting the service is not required.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like

Dim copyRange2 As Range
Dim copyRange3 As Range

Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)

copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")

put these near the other codings that are the same you can easily change the Ranges as you need.

I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.

I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

Add days to JavaScript Date

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.

If you want to just simply add n days to the date you have you are best to just go:

myDate.setDate(myDate.getDate() + n);

or the longwinded version

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.

Switch android x86 screen resolution

Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.

VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"

With the following appended to android kernel cmd:

UVESA_MODE=440x680 DPI=120

HTML 5 Geo Location Prompt in Chrome

As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files. Then you can use the geo location, provided you didn't turn it off in your settings.

How to differentiate single click event and double click event?

Instead of utilizing more ad-hoc states and setTimeout, turns out there is a native property called detail that you can access from the event object!

element.onclick = event => {
   if (event.detail === 1) {
     // it was a single click
   } else if (event.detail === 2) {
     // it was a double click
   }
};

Modern browsers and even IE-9 supports it :)

Source: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

How to run bootRun with spring profile via gradle task

For someone from internet, there was a similar question https://stackoverflow.com/a/35848666/906265 I do provide the modified answer from it here as well:

// build.gradle
<...>

bootRun {}

// make sure bootRun is executed when this task runs
task runDev(dependsOn:bootRun) {
    // TaskExecutionGraph is populated only after 
    // all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure-
    gradle.taskGraph.whenReady { graph ->
        logger.lifecycle('>>> Setting spring.profiles.active to dev')
        if (graph.hasTask(runDev)) {
            // configure task before it is executed
            bootRun {
                args = ["--spring.profiles.active=dev"]
            }
        }
    }
}

<...>

then in terminal:

gradle runDev

Have used gradle 3.4.1 and spring boot 1.5.10.RELEASE

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

How to check if any flags of a flag combination are set?

How about

if ((letter & Letters.AB) > 0)

?

Create an instance of a class from a string

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.

ReportClass report = new ReportClass();

The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass)); is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.

I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass available.

How to export specific request to file using postman?

If you want to export it as a file just do Any Collection (...) -> Export. There you should be able to choose collection version format and it will be exported in JSN file.

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

How can I combine multiple rows into a comma-delimited list in Oracle?

The WM_CONCAT function (if included in your database, pre Oracle 11.2) or LISTAGG (starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:

select listagg(table_name, ', ') within group (order by table_name) 
  from user_tables;

or

select wm_concat(table_name) 
  from user_tables;

More details/options

Link to documentation

How to create separate AngularJS controller files?

Although both answers are technically correct, I want to introduce a different syntax choice for this answer. This imho makes it easier to read what's going on with injection, differentiate between etc.

File One

// Create the module that deals with controllers
angular.module('myApp.controllers', []);

File Two

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl1
// to the module we got in the line above
.controller('Ctrl1', Ctrl1);

// Inject my dependencies
Ctrl1.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl1($scope, $http) {
  // Logic here
}

File Three

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl2
// to the module we got in the line above
.controller('Ctrl2', Ctrl2);

// Inject my dependencies
Ctrl2.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl2($scope, $http) {
  // Logic here
}

How to select all elements with a particular ID in jQuery?

You could also try wrapping the two div's in two div's with unique ids. Then select the div by $("#div1","#wraper1") and $("#div1","#wraper2")

Here you go:

<div id="wraper1">
<div id="div1">
</div>
<div id="wraper2">
<div id="div1">
</div>

Ant task to run an Ant target only if a file exists?

You can do it by ordering to do the operation with a list of files with names equal to the name(s) you need. It is much easier and direct than to create a special target. And you needn't any additional tools, just pure Ant.

<delete>
    <fileset includes="name or names of file or files you need to delete"/>
</delete>

See: FileSet.

Get div height with plain JavaScript

One option would be

const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);

What and When to use Tuple?

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.

Usually though you should create a class as this allows you to give useful names to each property. Code that extensively uses tuples will quickly become unreadable because the properties are called Item1, Item2, Item3, etc..

How to implement a ViewPager with different Fragments / Layouts

This is also fine:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    }
}


public class FragmentTab1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
        return rootView;
    }
}

class MyPagerAdapter extends FragmentPagerAdapter{

    public MyPagerAdapter(FragmentManager fragmentManager){
        super(fragmentManager);

    }
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch(position){
            case 0:
                FragmentTab1 fm =   new FragmentTab1();
                return fm;
            case 1: return new FragmentTab2();
            case 2: return new FragmentTab3();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

Are vectors passed to functions by value or by reference in C++

when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.

how to check confirm password field in form without reloading page

try using jquery like this

$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});

also add this line in head of html

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

Yes/No message box using QMessageBox

You can use the QMessage object to create a Message Box then add buttons :

QMessageBox msgBox;
msgBox.setWindowTitle("title");
msgBox.setText("Question");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
if(msgBox.exec() == QMessageBox::Yes){
  // do something
}else {
  // do something else
}

How to access to the parent object in c#

You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )
    )
    .setResultTransformer(Transformers.aliasToBean(entityClazz); 
    .list();

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

How to pass ArrayList of Objects from one to another activity using Intent in android?

Pass your object via Parcelable. And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:

public class Question implements Parcelable{
    public Question(Parcel in) {
        // put your data using = in.readString();
  this.operands = in.readString();;
    this.choices = in.readString();;
    this.userAnswerIndex = in.readString();;

    }

    public Question() {
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(operands);
        dest.writeString(choices);
        dest.writeString(userAnswerIndex);
    }

    public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {

        @Override
        public Question[] newArray(int size) {
            return new Question[size];
        }

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }
    };

}

Then pass your data like this:

Question question = new Question();
// put your data
  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putExtra("QuestionsExtra", question);
  startActivity(resultIntent);

And get your data like this:

Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
    question = extras.getParcelable("QuestionsExtra");
}

This will do!

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

If you are connecting from Windows Machine A to Windows Machine B (server with SQL Server installed) and are getting this error, you need to do the following:

On Machine B:

  1. Turn on the Windows service called "SQL Server Browser" and start the service Windows Services
  2. In Windows Firewall:
    • enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)
    • enable incoming port TCP 1433 (in case there is a telnet connection) Windows firewall
  3. In SQL Server Configuration Manager:
    • enable TCP/IP protocol for port 1433 Sql Server Configuration Manager

jQuery SVG vs. Raphael

For posterity, I'd like to note that I ended up choosing Raphael, because of the clean API and "free" IE support, and also because the active development looks promising (event support was just added in 0.7, for instance). However, I'll leave the question unanswered, and I'd still be interested to hear about others' experiences using Javascript + SVG libraries.

How can the Euclidean distance be calculated with NumPy?

With Python 3.8, it's very easy.

https://docs.python.org/3/library/math.html#math.dist

math.dist(p, q)

Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.

Roughly equivalent to:

sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

How to fill in proxy information in cntlm config file?

Once you generated the file, and changed your password, you can run as below,

cntlm -H

Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following

cntlm -v

How to apply box-shadow on all four sides?

Use this css code for all four sides: box-shadow: 0px 1px 7px 0px rgb(106, 111, 109);

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

linux script to kill java process

Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.

kill $(jps | grep <MainClass> | awk '{print $1}')

MainClass is a class in your running java program which contains the main method.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

github markdown colspan

I recently needed to do the same thing, and was pleased that the colspan worked fine with consecutive pipes ||

MultiMarkdown v4.5

Tested on v4.5 (latest on macports) and the v5.4 (latest on homebrew). Not sure why it doesn't work on the live preview site you provide.

A simple test that I started with was:

| Header ||
|--------------|
| 0 | 1 |

using the command:

multimarkdown -t html test.md > test.html

What does OpenCV's cvWaitKey( ) function do?

cvWaitKey(0) stops your program until you press a button.

cvWaitKey(10) doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey doesn't stop loop.

Normal use

char k;

k=cvWaitKey(0);

if(k == 'ESC')

with k you can see what key was pressed.

Sorting options elements alphabetically using jQuery

I know this topic is old but I think my answer can be useful for a lot of people.

Here is jQuery plugin made from Pointy's answer using ES6:

/**
 * Sort values alphabetically in select
 * source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
 */
$.fn.extend({
    sortSelect() {
        let options = this.find("option"),
            arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();

        arr.sort((o1, o2) => { // sort select
            let t1 = o1.t.toLowerCase(), 
                t2 = o2.t.toLowerCase();
            return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
        });

        options.each((i, o) => {
            o.value = arr[i].v;
            $(o).text(arr[i].t);
        });
    }
});

Use is very easy

$("select").sortSelect();

How to dynamically add a style for text-align using jQuery

You could also try the following to add an inline style to the element:

$(this).attr('style', 'text-align: center');

This should make sure that other styling rules aren't overriding what you thought would work. I believe inline styles usually get precedence.

EDIT: Also, another tool that may help you is Jash (http://www.billyreisinger.com/jash/). It gives you a javascript command prompt so you can ensure you easily test javascript statements and make sure you're selecting the right element, etc.

Assign format of DateTime with data annotations?

If your data field is already a DateTime datatype, you don't need to use [DataType(DataType.Date)] for the annotation; just use:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

on the jQuery, use datepicker for you calendar

    $(document).ready(function () {
        $('#StartDate').datepicker();
    });

on your HTML, use EditorFor helper:

    @Html.EditorFor(model => model.StartDate)

Linux Process States

Yes, the task gets blocked in the read() system call. Another task which is ready runs, or if no other tasks are ready, the idle task (for that CPU) runs.

A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.

Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.

Moving Git repository content to another repository preserving history

I am not very sure if what i did was right, but it worked anyways. I renamed repo2 folder present inside repo1, and committed the changes. In my case it was just one repo which i wanted to merge , so this approach worked. Later on, some path changes were done.

'adb' is not recognized as an internal or external command, operable program or batch file

For those using macOS, this osxdaily.com article shows several ways to add adb to the $PATH.

Here's the one I prefer:

  1. Add a file named adb to /etc/paths.d/ folder that just contains the path to adb's location: /Users/YourUserName/Library/Android/sdk/platform-tools/

    In a Terminal window, sudo vim /etc/paths.d/adb
    -> enter the path and save the file.

  2. Close/re-open Terminal in order for it to see the change.

How do I create a crontab through a script

(I don't have enough reputation to comment, so I'm adding at as an answer: feel free to add it as as comment next to his answer)

Joe Casadonte's one-liner is perfect, except if you run with set -e, i.e. if your script is set to fail on error, and if there are no cronjobs yet. In that case, the one-liner will NOT create the cronjob, but will NOT stop the script. The silent failure can be very misleading.

The reason is that crontab -l returns with a 1 return code, causing the subsequent command (the echo) not to be executed... thus the cronjob is not created. But since they are executed as a subprocess (because of the parenthesis) they don't stop the script.

(Interestingly, if you run the same command again, it will work: once you have executed crontab - once, crontab -l still outputs nothing, but it doesn't return an error anymore (you don't get the no crontab for <user> message anymore). So the subsequent echo is executed and the crontab is created)

In any case, if you run with set -e, the line must be:

(crontab -l 2>/dev/null || true; echo "*/5 * * * * /path/to/job -with args") | crontab -

python: restarting a loop

a = ['1', '2', '3']
ls = []
count = False

while ls != a :
    print(a[count])
    if a[count] != a[-1] :
        count = count + 1
    else :
        count = False

Restart while loop.