Programs & Examples On #Log4cxx

Apache log4cxx is a logging framework for C++ patterned after Apache log4j. Apache log4cxx uses Apache Portable Runtime for most platform-specific code and should be usable on any platform supported by APR. Apache log4cxx is licensed under the Apache License, an open source license certified by the Open Source Initiative.

java.net.ConnectException: Connection refused

You have to connect your client socket to the remote ServerSocket. Instead of

Socket clientSocket = new Socket("localhost", 5000);

do

Socket clientSocket = new Socket(serverName, 5000);

The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

Blank HTML SELECT without blank item in dropdown list

Just use disabled and/or hidden attributes:

<option selected disabled hidden style='display: none' value=''></option>
  • selected makes this option the default one.
  • disabled makes this option unclickable.
  • style='display: none' makes this option not displayed in older browsers. See: Can I Use documentation for hidden attribute.
  • hidden makes this option to don't be displayed in the drop-down list.

C++ program converts fahrenheit to celsius

Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9

Switch case with conditions

Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.

Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.

$('.next').click(function(){
        var imageToSlide = $('#imageSprite'); // Get id of image

        switch(true) {
            case (imageToSlide.hasClass('pos1')):
                imageToSlide.removeClass('pos1').addClass('pos2');
                break;
            case (imageToSlide.hasClass('pos2')):
                imageToSlide.removeClass('pos2').addClass('pos3');
                break;
            case (imageToSlide.hasClass('pos3')):
                imageToSlide.removeClass('pos3').addClass('pos4');
                break;
            case (imageToSlide.hasClass('pos4')):
                imageToSlide.removeClass('pos4').addClass('pos1');
        }
    }); ` 

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

AttributeError: 'DataFrame' object has no attribute

To get all the counts for all the columns in a dataframe, it's just df.count()

Getting JavaScript object key list

Note that in coffeescript this can be accomplished in all browsers and node as

k for k of obj

and thus

(1 for _ of obj).length

How to mark a build unstable in Jenkins when running shell scripts

I find the most flexible way to do this is by reading a file in the groovy post build plugin. enter image description here

import hudson.FilePath
import java.io.InputStream

def build = Thread.currentThread().executable

String unstable = null
if(build.workspace.isRemote()) {
    channel = build.workspace.channel;
    fp = new FilePath(channel, build.workspace.toString() + "/build.properties")
    InputStream is = fp.read()
    unstable = is.text.trim()
} else {
    fp = new FilePath(new File(build.workspace.toString() + "/build.properties"))
    InputStream is = fp.read()
    unstable = is.text.trim()
}

manager.listener.logger.println("Build status file: " + unstable)
if (unstable.equalsIgnoreCase('true')) {
    manager.listener.logger.println('setting build to unstable')
    manager.buildUnstable()
}

If the file contents are 'true' the build will be set to unstable. This will work on the local master and on any slaves you run the job on, and for any kind of scripts that can write to disk.

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;
}

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}

Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/

How to get current time and date in Android

For those who might rather prefer a customized format, you can use:

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

Whereas you can have DateFormat patterns such as:

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Best practices for Storyboard login screen, handling clearing of data upon logout

Create **LoginViewController** and **TabBarController**.

After creating the LoginViewController and TabBarController, we need to add a StoryboardID as “loginViewController” and “tabBarController” respectively.

Then I prefer to create the Constant struct:

struct Constants {
    struct StoryboardID {
        static let signInViewController = "SignInViewController"
        static let mainTabBarController = "MainTabBarController"
    }

    struct kUserDefaults {
        static let isSignIn = "isSignIn"
    }
}

In LoginViewController add IBAction:

@IBAction func tapSignInButton(_ sender: UIButton) {
    UserDefaults.standard.set(true, forKey: Constants.kUserDefaults.isSignIn)
    Switcher.updateRootViewController()
}

In ProfileViewController add IBAction:

@IBAction func tapSignOutButton(_ sender: UIButton) {
    UserDefaults.standard.set(false, forKey: Constants.kUserDefaults.isSignIn)
    Switcher.updateRootViewController()
}

In AppDelegate add line of code in didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Switcher.updateRootViewController()

    return true
}

Finally create Switcher class:

import UIKit

class Switcher {

    static func updateRootViewController() {

        let status = UserDefaults.standard.bool(forKey: Constants.kUserDefaults.isSignIn)
        var rootViewController : UIViewController?

        #if DEBUG
        print(status)
        #endif

        if (status == true) {
            let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
            let mainTabBarController = mainStoryBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.mainTabBarController) as! MainTabBarController
            rootViewController = mainTabBarController
        } else {
            let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
            let signInViewController = mainStoryBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.signInViewController) as! SignInViewController
            rootViewController = signInViewController
        }

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = rootViewController

    }

}

That is all!

Select2() is not a function

In my case, I was getting this error in my rails app when both webpacker and sprockets were trying to import jQuery. I didn't notice it until my code editor automatically tried to import jQuery into a webpacker module.

can not find module "@angular/material"

Change to,

import {MaterialModule} from '@angular/material';

DEMO

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

Validating parameters to a Bash script

The man page for test (man test) provides all available operators you can use as boolean operators in bash. Use those flags in the beginning of your script (or functions) for input validation just like you would in any other programming language. For example:

if [ -z $1 ] ; then
  echo "First parameter needed!" && exit 1;
fi

if [ -z $2 ] ; then
  echo "Second parameter needed!" && exit 2;
fi

How to add text to JFrame?

To create a label for text:

JLabel label1 = new JLabel("Test");

To change the text in the label:

label1.setText("Label Text");

And finally to clear the label:

label1.setText("");

And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...

Rename package in Android Studio

  1. Goto your AndroidManifest.xml file.
  2. Place your cursor in the package name like shown below. Don't select it, just place it.

    Enter image description here

  3. Then press Shift + F6 you will get a popup window as shown below select Rename package.

    Enter image description here

  4. Enter your new name and select Refactor. (Note since my cursor is on "something", only something is renamed.)

That's it done.

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

Fastest way to determine if an integer's square root is an integer

An integer problem deserves an integer solution. Thus

Do binary search on the (non-negative) integers to find the greatest integer t such that t**2 <= n. Then test whether r**2 = n exactly. This takes time O(log n).

If you don't know how to binary search the positive integers because the set is unbounded, it's easy. You starting by computing your increasing function f (above f(t) = t**2 - n) on powers of two. When you see it turn positive, you've found an upper bound. Then you can do standard binary search.

JavaScript null check

Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

A: Correct. Note that the following tests are equivalent:

data != null
data != undefined
data !== null && data !== undefined

See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.

FileNotFoundException..Classpath resource not found in spring?

This is due to spring-config.xml is not in classpath.

Add complete path of spring-config.xml to your classpath.

Also write command you execute to run your project. You can check classpath in command.

Rename multiple files in cmd

@echo off
for %%f in (*.txt) do (
    ren "%%~nf%%~xf" "%%~nf 1.1%%~xf"
)

Get current clipboard content?

Use the new clipboard API, via navigator.clipboard. It can be used like this:

navigator.clipboard.readText()
  .then(text => {
    console.log('Pasted content: ', text);
  })
  .catch(err => {
    console.error('Failed to read clipboard contents: ', err);
  });

Or with async syntax:

const text = await navigator.clipboard.readText();

Keep in mind that this will prompt the user with a permission request dialog box, so no funny business possible.

The above code will not work if called from the console. It only works when you run the code in an active tab. To run the code from your console you can set a timeout and click in the website window quickly:

setTimeout(async () => {
  const text = await navigator.clipboard.readText();
  console.log(text);
}, 2000);

Read more on the API and usage in the Google developer docs.

Spec

Duplicate headers received from server

Double quotes around the filename in the header is the standard per MDN web docs. Omitting the quotes creates multiple opportunities for problems arising from characters in the filename.

How to group dataframe rows into list in pandas groupby

Use any of the following groupby and agg recipes.

# Setup
df = pd.DataFrame({
  'a': ['A', 'A', 'B', 'B', 'B', 'C'],
  'b': [1, 2, 5, 5, 4, 6],
  'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df

   a  b  c
0  A  1  x
1  A  2  y
2  B  5  z
3  B  5  x
4  B  4  y
5  C  6  z

To aggregate multiple columns as lists, use any of the following:

df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)

           b          c
a                      
A     [1, 2]     [x, y]
B  [5, 5, 4]  [z, x, y]
C        [6]        [z]

To group-listify a single column only, convert the groupby to a SeriesGroupBy object, then call SeriesGroupBy.agg. Use,

df.groupby('a').agg({'b': list})  # 4.42 ms 
df.groupby('a')['b'].agg(list)    # 2.76 ms - faster

a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

How to delete a character from a string using Python

def kill_char(string, n): # n = position of which character you want to remove
    begin = string[:n]    # from beginning to n (n not included)
    end = string[n+1:]    # n+1 through end of string
    return begin + end
print kill_char("EXAMPLE", 3)  # "M" removed

I have seen this somewhere here.

Image height and width not working?

You have a class on your CSS that is overwriting your width and height, the class reads as such:

.postItem img {
    height: auto;
    width: 450px;
}

Remove that and your width/height properties on the img tag should work.

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Difference between binary tree and binary search tree

A binary search tree is a special kind of binary tree which exhibits the following property: for any node n, every descendant node's value in the left subtree of n is less than the value of n, and every descendant node's value in the right subtree is greater than the value of n.

Java Compare Two Lists

EDIT

Here are two versions. One using ArrayList and other using HashSet

Compare them and create your own version from this, until you get what you need.

This should be enough to cover the:

P.S: It is not a school assignment :) So if you just guide me it will be enough

part of your question.

continuing with the original answer:

You may use a java.util.Collection and/or java.util.ArrayList for that.

The retainAll method does the following:

Retains only the elements in this collection that are contained in the specified collection

see this sample:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;

public class Repeated {
    public static void main( String  [] args ) {
        Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
        Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));

        listOne.retainAll( listTwo );
        System.out.println( listOne );
    }
}

EDIT

For the second part ( similar values ) you may use the removeAll method:

Removes all of this collection's elements that are also contained in the specified collection.

This second version gives you also the similar values and handles repeated ( by discarding them).

This time the Collection could be a Set instead of a List ( the difference is, the Set doesn't allow repeated values )

import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;

class Repeated {
      public static void main( String  [] args ) {

          Collection<String> listOne = Arrays.asList("milan","iga",
                                                    "dingo","iga",
                                                    "elpha","iga",
                                                    "hafil","iga",
                                                    "meat","iga", 
                                                    "neeta.peeta","iga");

          Collection<String> listTwo = Arrays.asList("hafil",
                                                     "iga",
                                                     "binga", 
                                                     "mike", 
                                                     "dingo","dingo","dingo");

          Collection<String> similar = new HashSet<String>( listOne );
          Collection<String> different = new HashSet<String>();
          different.addAll( listOne );
          different.addAll( listTwo );

          similar.retainAll( listTwo );
          different.removeAll( similar );

          System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
      }
}

Output:

$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]

Two:[hafil, iga, binga, mike, dingo, dingo, dingo]

Similar:[dingo, iga, hafil]

Different:[mike, binga, milan, meat, elpha, neeta.peeta]

If it doesn't do exactly what you need, it gives you a good start so you can handle from here.

Question for the reader: How would you include all the repeated values?

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

how to delete default values in text field using selenium?

clear() didn't work for me. But this did:

input.sendKeys(Keys.CONTROL, Keys.chord("a")); //select all text in textbox
input.sendKeys(Keys.BACK_SPACE); //delete it
input.sendKeys("new text"); //enter new text

How do I set the value property in AngularJS' ng-options?

The ng-options directive does not set the value attribute on the <options> elements for arrays:

Using limit.value as limit.text for limit in limits means:

set the <option>'s label as limit.text
save the limit.value value into the select's ng-model

See Stack Overflow question AngularJS ng-options not rendering values.

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

How do I set the selected item in a drop down box

Simple and easy to understand example by using ternary operators to set selected value in php

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
  <option value="<?php echo $id;?>" <?php echo ($id==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

Tar a directory, but don't store full absolute paths in the archive

Seems -C option upto tar v2.8.3 does not work consistently on all the platforms (OSes). -C option is said to add directory to the archive but on Mac and Ubuntu it adds absolute path prefix inside generated tar.gz file.

tar target_path/file.tar.gz -C source_path/source_dir

Therefore the consistent and robust solution is to cd in to source_path (parent directory of source_dir) and run

tar target_path/file.tar.gz source_dir

or

tar -cf target_path/file.tar.gz source_dir

in your script. This will remove absolute path prefix in your generated tar.gz file's directory structure.

Is 'bool' a basic datatype in C++?

C is meant to be a step above assembly language. The C if-statement is really just syntactical sugar for "branch-if-zero", so the idea of booleans as an independent datatype was a foreign concept at the time. (1)

Even now, C/C++ booleans are usually little more than an alias for a single byte data type. As such, it's really more of a purposing label than an independent datatype.

(1) Of course, modern compilers are a bit more advanced in their handling of if statements. This is from the standpoint of C as a new language.

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Load data from txt with pandas

@Pietrovismara's solution is correct but I'd just like to add: rather than having a separate line to add column names, it's possible to do this from pd.read_csv.

df = pd.read_csv('output_list.txt', sep=" ", header=None, names=["a", "b", "c"])

No provider for Router?

Nothing works from this tread. "forRoot" doesn't help.

Sorry. Sorted this out. I've managed to make it work by setting correct "routes" for this "forRoot" router setup routine


    import {RouterModule, Routes} from '@angular/router';    
    import {AppComponent} from './app.component';
    
    const appRoutes: Routes = [
      {path: 'UI/part1/Details', component: DetailsComponent}
    ];
    
    @NgModule({
      declarations: [
        AppComponent,
        DetailsComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes)
      ],
      providers: [DetailsService],
      bootstrap: [AppComponent]
    })

Also may be helpful (spent some time to realize this) Optional route part:

    const appRoutes: Routes = [
       {path: 'UI/part1/Details', component: DetailsComponent},
       {path: ':project/UI/part1/Details', component: DetailsComponent}
    ];

Second rule allows to open URLs like
hostname/test/UI/part1/Details?id=666
and
hostname/UI/part1/Details?id=666

Been working as a frontend developer since 2012 but never stuck in a such over-complicated thing as angular2 (I have 3 years experience with enterprise level ExtJS)

Is jQuery $.browser Deprecated?

From the official documentation at http://api.jquery.com/jQuery.browser/:

This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.

You can use for example jquery-migrate-1.4.1.js to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Why is Git better than Subversion?

I have been dwelling in Git land lately, and I like it for personal projects, but I wouldn't be able to switch work projects to it yet from Subversion given the change in thinking of required from staff, without no pressing benefits. Moreover the biggest project we run in-house is extremely dependent on svn:externals which, from what I've seen so far, does not work so nicely and seamlessly in Git.

how to find array size in angularjs

You can find the number of members in a Javascript array by using its length property:

var number = $scope.names.length;

Docs - Array.prototype.length

py2exe - generate single executable file

You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.

That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.

For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.

Changing the row height of a datagridview

You can set the row height by code

dataGridView.RowTemplate.Height = 35;

or by property panel

enter image description here

How to use vagrant in a proxy environment?

If you actually do want your proxy configurations and plugin installations to be in your Vagrantfile, for example if you're making a Vagrantfile just for your corporate environment and can't have users editing environment variables, this was the answer for me:

ENV['http_proxy']  = 'http://proxyhost:proxyport'
ENV['https_proxy'] = 'http://proxyhost:proxyport'

# Plugin installation procedure from http://stackoverflow.com/a/28801317
required_plugins = %w(vagrant-proxyconf)

plugins_to_install = required_plugins.select { |plugin| not Vagrant.has_plugin? plugin }
if not plugins_to_install.empty?
  puts "Installing plugins: #{plugins_to_install.join(' ')}"
  if system "vagrant plugin install #{plugins_to_install.join(' ')}"
    exec "vagrant #{ARGV.join(' ')}"
  else
    abort "Installation of one or more plugins has failed. Aborting."
  end
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.proxy.http     = "#{ENV['http_proxy']}"
  config.proxy.https    = "#{ENV['https_proxy']}"
  config.proxy.no_proxy = "localhost,127.0.0.1"
  # and so on

(If you don't, just set them as environment variables like the other answers say and refer to them from env in config.proxy.http(s) directives.)

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

Automatically running a batch file as an administrator

Runas.exe won't work here. You can use VBScript to invoke the "Run as Administrator" shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:

elevatecmd.exe

http://blogs.technet.com/b/elevationpowertoys/

Uses for the '&quot;' entity in HTML

It is likely because they used a single function for escaping attributes and text nodes. &amp; doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:

Debug > Windows > Exception Settings

enter image description here

In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option

enter image description here

RecyclerView inside ScrollView is not working

This does the trick:

recyclerView.setNestedScrollingEnabled(false);

Changing the sign of a number in PHP?

I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:

$int = (($int > 0) ? -$int : $int);

EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:

/* I am not proposing you actually use functions called
   "makeNegative" and "makePositive"; I am just presenting
   the most direct solution in the form of two clearly named
   functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

http post - how to send Authorization header?

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

Basic http file downloading and saving to disk in python?

import urllib
urllib.request.urlretrieve("https://raw.githubusercontent.com/dnishimoto/python-deep-learning/master/list%20iterators%20and%20generators.ipynb", "test.ipynb")

downloads a single raw juypter notebook to file.

Responding with a JSON object in Node.js (converting object/array to JSON string)

var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

How to select and change value of table cell with jQuery?

i was looking for changing second row html and you can do cascading selector

$('#tbox1 tr:nth-child(2) td').html(11111)

Make a nav bar stick

Give headercss position fixed.

.headercss {
    width: 100%;
    height: 320px;
    background-color: #000000;
    position: fixed;
    top:0
}

Then give the content container a 320px padding-top, so it doesn't get behind the header.

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This question is a few years old, and there are some good suggestions for workarounds, but I didn't really notice any answers that address the core of the original question head-on. So:

  • Providing a "universal" method for viewing source in a feature phone browser (or even arbitrary third-party smartphone browser) is impossible because "view source" — via any method — is a feature implemented in the browser. So how it's accessed, or even if it can be accessed, is up to the developers of the browser. I'm sure there are plenty of browsers that intentionally prevent the user from viewing page source, and if so then you're out of luck, except maybe for workarounds like the ones offered here.

  • Workarounds such as "view source" apps external to the browser, while useful in some cases, are at best an imperfect partial solution to the original request. It's never certain that any such app will display the source of the page in the same form as it's loaded by the phone's browser.

    Modern web content changes itself in all manner of ways through browser detection, session management, etc. so that the source loaded by any external app can never be relied on to represent the source as loaded by a different app. If you're going to use an external app to load a page because you want to see the source, you might as well just use Chrome (or, on an iOS device, Safari) instead.

How to set the current working directory?

Try os.chdir

os.chdir(path)

        Change the current working directory to path. Availability: Unix, Windows.

How to keep the console window open in Visual C++?

(Some options are may be called by different names. I do not use the english version)

I had the same problem, when I created projects with the option "empty project", Create project as "Win32-console application" instead of "empty project" . In the dialog which pops up now, you press "continue" and after that you may check the option "empty project" and press confirm. After that CTRL + F5 will open a console which does not close automatically.

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

Ignore duplicates when producing map using streams

For grouping by Objects

Map<Integer, Data> dataMap = dataList.stream().collect(Collectors.toMap(Data::getId, data-> data, (data1, data2)-> {LOG.info("Duplicate Group For :" + data2.getId());return data1;}));

HTML.ActionLink method

I think what you want is this:

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

two arguments have been switched around

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

how to install tensorflow on anaconda python 3.6

UPDATE: TensorFlow supports Python 3.6 on Windows since version 1.2.0 (see the release notes)


TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion.

The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source.

If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in: conda create --name tensorflow python=3.5 activate tensorflow pip install tensorflow-gpu

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

How to check if mod_rewrite is enabled in php?

Copy this piece of code and run it to find out.


<?php
 if(!function_exists('apache_get_modules') ){ phpinfo(); exit; }
 $res = 'Module Unavailable';
 if(in_array('mod_rewrite',apache_get_modules())) 
 $res = 'Module Available';
?>
<html>
<head>
<title>A mod_rewrite availability check !</title></head>
<body>
<p><?php echo apache_get_version(),"</p><p>mod_rewrite $res"; ?></p>
</body>
</html>

Add CSS or JavaScript files to layout head from views or partial views

Sadly, this is not possible by default to use section as another user suggested, since a section is only available to the immediate child of a View.

What works however is implementing and redefining the section in every view, meaning:

section Head
{
    @RenderSection("Head", false)
}

This way every view can implement a head section, not just the immediate children. This only works partly though, especially with multiple partials the troubles begin (as you have mentioned in your question).

So the only real solution to your problem is using the ViewBag. The best would probably be a seperate collection (list) for CSS and scripts. For this to work, you need to ensure that the List used is initialized before any of the views are executed. Then you can can do things like this in the top of every view/partial (without caring if the Scripts or Styles value is null:

ViewBag.Scripts.Add("myscript.js");
ViewBag.Styles.Add("mystyle.css");

In the layout you can then loop through the collections and add the styles based on the values in the List.

@foreach (var script in ViewBag.Scripts)
{
    <script type="text/javascript" src="@script"></script>
}
@foreach (var style in ViewBag.Styles)
{
    <link href="@style" rel="stylesheet" type="text/css" />
}

I think it's ugly, but it's the only thing that works.

******UPDATE**** Since it starts executing the inner views first and working its way out to the layout and CSS styles are cascading, it would probably make sense to reverse the style list via ViewBag.Styles.Reverse().

This way the most outer style is added first, which is inline with how CSS style sheets work anyway.

How to declare an array of objects in C#

you need to initialize the object elements of the array.

GameObject[] houses = new GameObject[200];

for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}

Of course you initialize elements selectively using different constructors anywhere else before you reference them.

Renew Provisioning Profile

In addition to the other solutions I needed to edit the code signing on the main project and the Target file to get the app building to the device again after an expired provisioning profile.

::Delete the old expired profiles

::Add the new profile with the Organizer

::Clean All Targets

::Get Info -> Code Signing on both the main project and the Target

::Build and Run

Unicode character for "X" cancel / close?

&times; is better than &#10006; as &#10006; behaves strangely in Edge and Internet explorer (tested in IE11). It doesn't get the right color and is replaced by an "emoji"

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

My problem solved after adding

 dexOptions {
        incremental true
        javaMaxHeapSize "4g"
        preDexLibraries true
        dexInProcess = true
    }

in Build.Gradle file

how do I query sql for a latest record date for each user

You would use aggregate function MAX and GROUP BY

SELECT username, MAX(date), value FROM tablename GROUP BY username, value

int to hex string

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

C# compiler error: "not all code paths return a value"

class Program
{
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;


    public double[] CheckSorting()
    {
        for(int i = 1; i < a.Length; i++)
        {
            if (a[i] < a[i - 1])
                result = b;
            else
                result = a;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Program checkSorting = new Program();
        checkSorting.CheckSorting();
        Console.ReadLine();
    }
}

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

What does the servlet <load-on-startup> value signify

As stated on other answer and this load-on-startup article zero is acceptable and in the absent of any other servlet this will take priority on loading and loaded during deployment. Best use of load-on statup is to load servlets which takes longer time to initialize well before first request come like servlets which creates connection pool or make network call or hold bulky resource, this will significantly reduce response time for first few request.

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

Retrieving parameters from a URL

I didn't want to mess with additional libraries. Simple ways suggested here didn't work out either. Finally, not on the request object, but I could get a GET parameter w/o all that hassle via self.GET.get('XXX'):

...
def get_context_data(self, **kwargs):
    context = super(SomeView, self).get_context_data(**kwargs)
    context['XXX'] = self.GET.get('XXX')
...

Python 2.7.18, Django 1.11.20

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

Android Button click go to another xml page

There is more than one way to do this.

Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html

At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.

If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.

How to check file input size with jQuery?

I am posting my solution too, used for an ASP.NET FileUpload control. Perhaps someone will find it useful.

    $(function () {        
    $('<%= fileUploadCV.ClientID %>').change(function () {

        //because this is single file upload I use only first index
        var f = this.files[0]

        //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes)
        if (f.size > 8388608 || f.fileSize > 8388608)
        {
           //show an alert to the user
           alert("Allowed file size exceeded. (Max. 8 MB)")

           //reset file upload control
           this.value = null;
        }
    })
});

How to change Java version used by TOMCAT?

When you open catalina.sh / catalina.bat, you can see :

Environment Variable Prequisites

JAVA_HOME Must point at your Java Development Kit installation.

So, set your environment variable JAVA_HOME to point to Java 6. Also make sure JRE_HOME is pointing to the same target, if it is set.

Update: since you are on Windows, see here for how to manage your environment variables

addEventListener for keydown on Canvas

Set the tabindex of the canvas element to 1 or something like this

<canvas tabindex='1'></canvas>

It's an old trick to make any element focusable

how to check if a datareader is null or empty

if (myReader["Additional"] != DBNull.Value)
{
    ltlAdditional.Text = "contains data";
}
else
{
     ltlAdditional.Text = "is null";
}

Setting background colour of Android layout element

If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:

android:background="@android:color/black"

There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.

Setting up a values/colors.xml file and using straight Hex like explained above will still work.

How to get line count of a large file cheaply in Python?

Just to complete the above methods I tried a variant with the fileinput module:

import fileinput as fi   
def filecount(fname):
        for line in fi.input(fname):
            pass
        return fi.lineno()

And passed a 60mil lines file to all the above stated methods:

mapcount : 6.1331050396
simplecount : 4.588793993
opcount : 4.42918205261
filecount : 43.2780818939
bufcount : 0.170812129974

It's a little surprise to me that fileinput is that bad and scales far worse than all the other methods...

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

As was said you need to remove the FKs before. On Mysql do it like this:

ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;

ALTER TABLE `table_name` DROP INDEX `id_name_fk`;

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

AssertionError: View function mapping is overwriting an existing endpoint function: main

Adding @wraps(f) above the wrapper function solved my issue.

def list_ownership(f):
    @wraps(f)
    def decorator(*args,**kwargs):
        return f(args,kwargs)
    return decorator

How link to any local file with markdown syntax?

After messing around with @BringBackCommodore64 answer I figured it out

[link](file:///d:/absolute.md)    # absolute filesystem path
[link](./relative1.md)            # relative to opened file
[link](/relativeToProject.md)     # relative to opened project

All of them tested in Visual Studio Code and working,

Note: The absolute path works in editor but doesn't work in markdown preview mode!

PHP: How to remove all non printable characters in a string?

The regex into selected answer fail for Unicode: 0x1d (with php 7.4)

a solution:

<?php
        $ct = 'différents'."\r\n test";

        // fail for Unicode: 0x1d
        $ct = preg_replace('/[\x00-\x1F\x7F]$/u', '',$ct);

        // work for Unicode: 0x1d
        $ct =  preg_replace( '/[^\P{C}]+/u', "",  $ct);

        // work for Unicode: 0x1d and allow line break
        $ct =  preg_replace( '/[^\P{C}\n]+/u', "",  $ct);

        echo $ct;

from: UTF 8 String remove all invisible characters except newline

python-pandas and databases like mysql

MySQL example:

import MySQLdb as db
from pandas import DataFrame
from pandas.io.sql import frame_query

database = db.connect('localhost','username','password','database')
data     = frame_query("SELECT * FROM data", database)

Git "error: The branch 'x' is not fully merged"

I had this happen to me today, as I was merging my very first feature branch back into master. As some said in a thread elsewhere on SO, the trick was switching back to master before trying to delete the branch. Once in back in master, git was happy to delete the branch without any warnings.

How to run mvim (MacVim) from Terminal?

I don't think I'd to add anything to the path, did

brew install macvim

mvim -v

should then open macvim in the terminal, you can also go ahead and alias that

alias vim='mvim -v'

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

insert/delete/update trigger in SQL server

I use that for all status (update, insert and delete)

CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE 
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Activity  NVARCHAR (50)

-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
    SET @Activity = 'UPDATE'
END

-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
    SET @Activity = 'INSERT'
END

-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
    SET @Activity = 'DELETE'
END



-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                 UNION 
                                                 SELECT * FROM deleted
                                                 ) AS A ORDER BY A.Date DESC
                            ) AS T


-- try catch
BEGIN TRY 

    INSERT INTO MyTable  (
           [Code]
          ,[Name]
           .....
          ,[Activity])
    SELECT [Code]
          ,[Name]
          ,@Activity 
    FROM #tmpTbl

END TRY BEGIN CATCH END CATCH


-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

SET NOCOUNT OFF;
END

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

How can I check if PostgreSQL is installed or not via Linux script?

For many years I used the command:

ps aux | grep postgres

On one hand it is useful (for any process) and gives useful info (but from process POV). But on the other hand it is for checking if the server you know, you already installed is running.

At some point I found this tutorial, where the usage of the locate command is shown. It looks like this command is much more to the point for this case.

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

Here's the exact definition of UsedRange (MSDN reference) :

Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.

So basically, what that line does is :

  1. .UsedRange -> "Draws" a box around the outer-most cells with content inside.
  2. .Columns -> Selects the entire columns of those cells
  3. .Count -> Returns an integer corresponding to how many columns there are (in this selection)
  4. - 8 -> Subtracts 8 from the previous integer.

I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.

Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.

Checking Bash exit status of several commands efficiently

What do you mean by "drop out and echo the error"? If you mean you want the script to terminate as soon as any command fails, then just do

set -e    # DON'T do this.  See commentary below.

at the start of the script (but note warning below). Do not bother echoing the error message: let the failing command handle that. In other words, if you do:

#!/bin/sh

set -e    # Use caution.  eg, don't do this
command1
command2
command3

and command2 fails, while printing an error message to stderr, then it seems that you have achieved what you want. (Unless I misinterpret what you want!)

As a corollary, any command that you write must behave well: it must report errors to stderr instead of stdout (the sample code in the question prints errors to stdout) and it must exit with a non-zero status when it fails.

However, I no longer consider this to be a good practice. set -e has changed its semantics with different versions of bash, and although it works fine for a simple script, there are so many edge cases that it is essentially unusable. (Consider things like: set -e; foo() { false; echo should not print; } ; foo && echo ok The semantics here are somewhat reasonable, but if you refactor code into a function that relied on the option setting to terminate early, you can easily get bitten.) IMO it is better to write:

 #!/bin/sh

 command1 || exit
 command2 || exit
 command3 || exit

or

#!/bin/sh

command1 && command2 && command3

Templated check for the existence of a class member function?

template<class T>
auto optionalToString(T* obj)
->decltype( obj->toString(), std::string() )
{
     return obj->toString();
}

template<class T>
auto optionalToString(T* obj)
->decltype( std::string() )
{
     throw "Error!";
}

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

Is it possible to get element from HashMap by its position?

I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

public Object getElementAt(LinkedHashMap map, int index) {
    for (Map.Entry entry : map.entrySet()) {
        if (index-- == 0) {
            return entry.value();
        }
    }
    return null;
}

Links in <select> dropdown options

This is an old question, I know but for 2019 peeps:

Like above if you just want to change the URL you can do this:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

But if you want it to act like an a tag and so you can do "./page", "#bottom" or "?a=567" use window.location.replace()

<select onChange="window.location.redirect(this.value)">
    <option value="..">back</option>
    <option value="./list">list</option>
    <option value="#bottom">bottom</option>
</select>

How to import a module given the full path?

There's a package that's dedicated to this specifically:

from thesmuggler import smuggle

# À la `import weapons`
weapons = smuggle('weapons.py')

# À la `from contraband import drugs, alcohol`
drugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')

# À la `from contraband import drugs as dope, alcohol as booze`
dope, booze = smuggle('drugs', 'alcohol', source='contraband.py')

It's tested across Python versions (Jython and PyPy too), but it might be overkill depending on the size of your project.

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

disabling spring security in spring boot app

Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed

Section vs Article HTML5

I'd use <article> for a text block that is totally unrelated to the other blocks on the page. <section>, on the other hand, would be a divider to separate a document which have are related to each other.

Now, i'm not sure what you have in your videos, newsfeed etc, but here's an example (there's no REAL right or wrong, just a guideline of how I use these tags):

<article>
    <h1>People</h1>
    <p>text about people</p>
    <section>
        <h1>fat people</h1>
        <p>text about fat people</p>
    </section>
    <section>
        <h1>skinny people</p>
        <p>text about skinny people</p>
    </section>
</article>
<article>
    <h1>Cars</h1>
    <p>text about cars</p>
    <section>
        <h1>Fast Cars</h1>
        <p>text about fast cars</p>
    </section>
</article>

As you can see, the sections are still relevant to each other, but as long as they're inside a block that groups them. Sections DONT have to be inside articles. They can be in the body of a document, but i use sections in the body, when the whole document is one article.

e.g.

<body>
    <h1>Cars</h1>
    <p>text about cars</p>
    <section>
        <h1>Fast Cars</h1>
        <p>text about fast cars</p>
    </section>
</body>

Hope this makes sense.

Can I use VARCHAR as the PRIMARY KEY?

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

An efficient compression algorithm for short text strings

Huffman has a static cost, the Huffman table, so I disagree it's a good choice.

There are adaptative versions which do away with this, but the compression rate may suffer. Actually, the question you should ask is "what algorithm to compress text strings with these characteristics". For instance, if long repetitions are expected, simple Run-Lengh Encoding might be enough. If you can guarantee that only English words, spaces, punctiation and the occasional digits will be present, then Huffman with a pre-defined Huffman table might yield good results.

Generally, algorithms of the Lempel-Ziv family have very good compression and performance, and libraries for them abound. I'd go with that.

With the information that what's being compressed are URLs, then I'd suggest that, before compressing (with whatever algorithm is easily available), you CODIFY them. URLs follow well-defined patterns, and some parts of it are highly predictable. By making use of this knowledge, you can codify the URLs into something smaller to begin with, and ideas behind Huffman encoding can help you here.

For example, translating the URL into a bit stream, you could replace "http" with the bit 1, and anything else with the bit "0" followed by the actual procotol (or use a table to get other common protocols, like https, ftp, file). The "://" can be dropped altogether, as long as you can mark the end of the protocol. Etc. Go read about URL format, and think on how they can be codified to take less space.

Shell Script — Get all files modified after <date>

well under linux try reading man page of the find command

man find

something like this should

 find . -type f -mtime -7 -print -exec cat {} \; | tar cf - | gzip -9

and you have it

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

find: missing argument to -exec

You have to put a space between {} and \;

So the command will be like:

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 && rm {} \;

Replace only some groups with Regex

go through the below coding to get the separate group replacement.

new_bib = Regex.Replace(new_bib, @"(?s)(\\bibitem\[[^\]]+\]\{" + pat4 + @"\})[\s\n\v]*([\\\{\}a-zA-Z\.\s\,\;\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']{20,70})", delegate(Match mts)
                    {
                           var fg = mts.Groups[0].Value.ToString(); 
                           var fs = mts.Groups[1].Value.ToString();
                           var fss = mts.Groups[2].Value.ToString();
                               fss = Regex.Replace(fss, @"[\\\{\}\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']+", "");
                           return "<augroup>" + fss + "</augroup>" + fs;
                    }, RegexOptions.IgnoreCase);

Insert new item in array on any position in PHP

This is what worked for me for the associative array:

/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}

The function source - this blog post. There's also handy function to insert BEFORE specific key.

How to calculate the CPU usage of a process by PID in Linux from C?

You need to parse out the data from /proc/<PID>/stat. These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
..............................................................................
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

You're probably after utime and/or stime. You'll also need to read the cpu line from /proc/stat, which looks like:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a time_total measure.

Read both utime and stime for the process you're interested in, and read time_total from /proc/stat. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:

user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

Make sense?

Official way to ask jQuery wait for all images to load before executing something

I would recommend using imagesLoaded.js javascript library.

Why not use jQuery's $(window).load()?

As ansered on https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951

It's a matter of scope. imagesLoaded allows you target a set of images, whereas $(window).load() targets all assets — including all images, objects, .js and .css files, and even iframes. Most likely, imagesLoaded will trigger sooner than $(window).load() because it is targeting a smaller set of assets.

Other good reasons to use imagesloaded

  • officially supported by IE8+
  • license: MIT License
  • dependencies: none
  • weight (minified & gzipped) : 7kb minified (light!)
  • download builder (helps to cut weight) : no need, already tiny
  • on Github : YES
  • community & contributors : pretty big, 4000+ members, although only 13 contributors
  • history & contributions : stable as relatively old (since 2010) but still active project

Resources

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

How do I install chkconfig on Ubuntu?

In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.

So instead of:

chkconfig enable apache2

You should look for the service name, and then enable it

systemctl status apache2
systemctl enable apache2.service

Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.

Check if a Python list item contains a string inside another string

Use the __contains__() method of Pythons string class.:

a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
    if i.__contains__("abc") :
        print(i, " is containing")

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

You basically have four potential solutions to fix a "javax.net.ssl.SSLHandshakeException: " exception on Android

  1. Trust all certificates. Don't do this, unless you really know what you're doing.
  2. Create a custom SSLSocketFactory that trusts only your certificate. This works as long as you know exactly which servers you're going to connect to, but as soon as you need to connect to a new server with a different SSL certificate, you'll need to update your app.
  3. Create a Keystore file that contains Android's "master list" of certificates, then add your own. If any of those certs expire down the road, you are responsible for updating them in your app. I can't think of a reason to do this.
  4. Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default. This is well explained in click here

Also, I want to elaborate more to point number 1. We can selectively skip some domain using manifest network config as explain:

  1. Create a file "network_security_config.xml" in xml folder in res folder with following content.

       <network-security-config xmlns:tools="http://schemas.android.com/tools"
         xmlns:android="http://schemas.android.com/apk/res/android">
             <domain-config>
              <domain includeSubdomains="true">191.1.1.0</domain>
              <domain includeSubdomains="true">your_domain</domain>
             <trust-anchors>
                 <certificates src="system" />
                 <certificates src="user" />
             </trust-anchors>
         </domain-config>
     </network-security-config>
    
  2. Add "network_security_config.xml" to application tag in manifest as:

    android:networkSecurityConfig="@xml/network_security_config"

Thats it..done!!. You successfully skipped the SSL certificate.

Create a git patch from the uncommitted changes in the current working directory

If you haven't yet commited the changes, then:

git diff > mypatch.patch

But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff output. So, one way to do a patch is to stage everything for a new commit (git add each file, or just git add .) but don't do the commit, and then:

git diff --cached > mypatch.patch

Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):

git diff --cached --binary > mypatch.patch

You can later apply the patch:

git apply mypatch.patch

Insert data into a view (SQL Server)

Inserting 'test' to name will lead to inserting NULL values to other columns of the base table which wont be correct as Id is a PRIMARY KEY and it cannot have NULL value.

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Java heap size descriptions (xms, xmx, xmn)

-Xms size in bytes

Example : java -Xms32m

Sets the initial size of the Java heap. The default size is 2097152 (2MB). The values must be a multiple of, and greater than, 1024 bytes (1KB). (The -server flag increases the default size to 32M.)

-Xmn size in bytes

Example : java -Xmx2m

Sets the initial Java heap size for the Eden generation. The default value is 640K. (The -server flag increases the default size to 2M.)

-Xmx size in bytes

Example : java -Xmx2048m

Sets the maximum size to which the Java heap can grow. The default size is 64M. (The -server flag increases the default size to 128M.) The maximum heap limit is about 2 GB (2048MB).

Java memory arguments (xms, xmx, xmn) formatting

When setting the Java heap size, you should specify your memory argument using one of the letters “m” or “M” for MB, or “g” or “G” for GB. Your setting won’t work if you specify “MB” or “GB.” Valid arguments look like this:

-Xms64m or -Xms64M -Xmx1g or -Xmx1G Can also use 2048MB to specify 2GB Also, make sure you just use whole numbers when specifying your arguments. Using -Xmx512m is a valid option, but -Xmx0.5g will cause an error.

This reference can be helpful for someone.

How to view the stored procedure code in SQL Server Management Studio

Use this query:

SELECT object_definition(object_id) AS [Proc Definition]
FROM sys.objects 
WHERE type='P'

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

ViewFlipper loads all images into memory during layout inflating. Because my images are big it takes many memory, I replaced ViewFlipper with ImageSwitcher which can change the images with animation like ViewFlipper but it loads only one image at the time.

Should import statements always be at the top of a module?

Just to complete Moe's answer and the original question:

When we have to deal with circular dependences we can do some "tricks". Assuming we're working with modules a.py and b.py that contain x() and b y(), respectively. Then:

  1. We can move one of the from imports at the bottom of the module.
  2. We can move one of the from imports inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).
  3. We can change one of the two from imports to be an import that looks like: import a

So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this "tricks" include a comment, it's always welcome! :)

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

jQuery 1.9 .live() is not a function

The jQuery API documentation lists live() as deprecated as of version 1.7 and removed as of version 1.9: link.

version deprecated: 1.7, removed: 1.9

Furthermore it states:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Another good way of dealing with Lion's hidden scroll bars is to display a prompt to scroll down. It doesn't work with small scroll areas such as text fields but well with large scroll areas and keeps the overall style of the site. One site doing this is http://versusio.com, just check this example page and wait 1.5 seconds to see the prompt:

http://versusio.com/en/samsung-galaxy-nexus-32gb-vs-apple-iphone-4s-64gb

The implementation isn't hard but you have to take care, that you don't display the prompt when the user has already scrolled.

You need jQuery + Underscore and

$(window).scroll to check if the user already scrolled by himself,

_.delay() to trigger a delay before you display the prompt -- the prompt shouldn't be to obtrusive

$('#prompt_div').fadeIn('slow') to fade in your prompt and of course

$('#prompt_div').fadeOut('slow') to fade out when the user scrolled after he saw the prompt

In addition, you can bind Google Analytics events to track user's scrolling behavior.

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

What is the worst programming language you ever worked with?

I also forgot to mention prova and yes, it is a mixed language. It is a prolog implementation built on top of java which means that it is damn slow. They sell it by its ability to call java functions, the sad part is that you lose backtracking when you do it. So, all in all, you lose the strengths of both languages. I still don't understand why the authors didn't choose just an implementation of prolog inside java, so you can call prolog code from java instead of build your own interpreter.

Get JSON object from URL

When you are using curl sometimes give you 403 (access forbidden) Solved by adding this line to emulate browser.

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');

Hope this help someone.

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

Java String - See if a string contains only numbers and not letters

Here is a sample. Find only the digits in a String and Process formation as needed.

text.replaceAll("\\d(?!$)", "$0 ");

For more info check google Docs https://developer.android.com/reference/java/util/regex/Pattern Where you can use Pattern

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

Solution:

use incognito new tab then test it again.

reason:

in my case another user logged in with my admin panel

How to convert an OrderedDict into a regular dict in python3

If somehow you want a simple, yet different solution, you can use the {**dict} syntax:

from collections import OrderedDict

ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}

jQuery equivalent to Prototype array.last()

I know the answer is already given, but I think I've got another solution for this. You could take the array, reverse it and output the first array item like this:

var a = [1,2,3,4];
var lastItem = a.reverse()[0];

Works fine for me.

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

How do I search for names with apostrophe in SQL Server?

Double them to escape;

SELECT *
  FROM Header
 WHERE userID LIKE '%''%'

Adding a collaborator to my free GitHub account?

Clear Instructions On How to Add A Collaborator - 2020 Update

Pictures are worth a thousand words. Let's put that to the test:

Picture Instructions (Click to Zoom in):

Picture Instructions

.......and videos/gifs are worth another thousand more:

Gif Instructions (Click to Zoom in):

Hopefully the pictures/gif make it easier for you to configure this!

enter image description here

IIS - can't access page by ip address instead of localhost

In IIS Manager, I added a binding to the site specifying the IP address. Previously, all my bindings were host names.

phpinfo() is not working on my CentOS server

For people who have no experience in building websites (like me) I tried a lot, only to find out that I hadn't used the .php extension, but the .html extension.

Table header to stay fixed at the top when user scrolls it out of view with jQuery

I've tried most of these solutions, and eventually found (IMO) the best, modern, solution:

CSS grids


With CSS grids, you can define a 'grid', and you can finally create a nice, javascript-free, cross-browser solution for a table with a fixed header, and scrollable content. The header height can even dynamic.

CSS: Display as grid, and set the number of template-rows:

.grid {
    display: grid;
    grid-template-rows: 50px auto; // For fixed height header
    grid-template-rows: auto auto; // For dynamic height header
}

HTML: Create a grid container and the number of defined rows:

<div class="grid">
    <div></div>
    <div></div>
</div>

Here is working example:

CSS

body {
  margin: 0px;
  padding: 0px;
  text-align: center;
}

.table {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-rows: 50px auto;
}
.table-heading {
  background-color: #ddd;
}
.table-content {
  overflow-x: hidden;
  overflow-y: scroll;
}

HTML

<html>
    <head>
    </head>
    <body>
        <div class="table">
            <div class="table-heading">
                HEADING
            </div>
            <div class="table-content">
                CONTENT - CONTENT - CONTENT <br/>
                CONTENT - CONTENT - CONTENT <br/>
                CONTENT - CONTENT - CONTENT <br/>
                CONTENT - CONTENT - CONTENT <br/>
                CONTENT - CONTENT - CONTENT <br/>
                CONTENT - CONTENT - CONTENT <br/>
            </div>
        </div>
    </body>
</html>

Waiting for HOME ('android.process.acore') to be launched

None of these solutions worked for me. Instead, what worked was to go to a command line tool (or terminal in Mac), CD into the SDK/platform-tools directory, and then run this:

adb kill-server

then run this:

adb start-server

After I did this everything worked again. Why? Who knows.

On my MAC the path to the platform-tools folder was $HOME/Installations/adt-bundle-mac-x86_64-20130522/sdk/platform-tools It will probably be somewhere else on your machine.

I also found this page that presents some helpful steps:

http://android.okhelp.cz/android-emulator-wont-run-application-started-from-eclipse/

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

"unrecognized selector sent to instance" error in Objective-C

How to debug ‘unrecognized selector send to instance’

In most of the cases Xcode do not take us to the exact line where this issue happen. When app crash you won’t see the line of code that caused this rather you will be taken to App delegate class, with error output something following:

[UITableViewCellContentView image]: unrecognized selector sent to instance

or

[__NSDictionaryI objectAtIndex:] unrecognized selector sent to instance

or

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestApp.MyViewController viewDidLoad:]: unrecognized selector sent to instance 0xDABCDD'

How to find line of code causing this:

Go to breakpoint navigator. Click ‘+’ option. click ‘Exception Breakpoint’. An new widget like following will apear.

enter image description here

Add following condition block:

-[NSObject(NSObject) doesNotRecognizeSelector:]

enter image description here

You can also put breakpoint for all exception. Now run your code again. this time, breakpoint will trigger when this exception occurs.

WRITTEN BY: Prafulla Singh

Full explanition: https://prafullkumar77.medium.com/how-to-debug-unrecognized-selector-send-to-instance-402473bc23d

MySQL 'create schema' and 'create database' - Is there any difference

So, there is no difference between MySQL "database" and MySQL "schema": these are two names for the same thing - a namespace for tables and other DB objects.

For people with Oracle background: MySQL "database" a.k.a. MySQL "schema" corresponds to Oracle schema. The difference between MySQL and Oracle CREATE SCHEMA commands is that in Oracle the CREATE SCHEMA command does not actually create a schema but rather populates it with tables and views. And Oracle's CREATE DATABASE command does a very different thing than its MySQL counterpart.

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

If the .stop() is deprecated then I don't think we should re-add it like @MuazKhan dose. It's a reason as to why things get deprecated and should not be used anymore. Just create a helper function instead... Here is a more es6 version

function stopStream (stream) {
    for (let track of stream.getTracks()) { 
        track.stop()
    }
}

MySQL DISTINCT on a GROUP_CONCAT()

Other answers to this question do not return what the OP needs, they will return a string like:

test1 test2 test3 test1 test3 test4

(notice that test1 and test3 are duplicated) while the OP wants to return this string:

test1 test2 test3 test4

the problem here is that the string "test1 test3" is duplicated and is inserted only once, but all of the others are distinct to each other ("test1 test2 test3" is distinct than "test1 test3", even if some tests contained in the whole string are duplicated).

What we need to do here is to split each string into different rows, and we first need to create a numbers table:

CREATE TABLE numbers (n INT);
INSERT INTO numbers VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);

then we can run this query:

SELECT
  SUBSTRING_INDEX(
    SUBSTRING_INDEX(tableName.categories, ' ', numbers.n),
    ' ',
    -1) category
FROM
  numbers INNER JOIN tableName
  ON
    LENGTH(tableName.categories)>=
    LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1;

and we get a result like this:

test1
test4
test1
test1
test2
test3
test3
test3

and then we can apply GROUP_CONCAT aggregate function, using DISTINCT clause:

SELECT
  GROUP_CONCAT(DISTINCT category ORDER BY category SEPARATOR ' ')
FROM (
  SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
  FROM
    numbers INNER JOIN tableName
    ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
  ) s;

Please see fiddle here.

What is the most efficient way to concatenate N arrays?

Easily with the concat function:

var a = [1,2,3];
var b = [2,3,4];
a = a.concat(b);
>> [1,2,3,2,3,4]

Selecting last element in JavaScript array

use es6 deconstruction array with the spread operator

var last = [...yourArray].pop();

note that yourArray doesn't change.

What good are SQL Server schemas?

I tend to agree with Brent on this one... see this discussion here. http://www.brentozar.com/archive/2010/05/why-use-schemas/

In short... schemas aren't terribly useful except for very specific use cases. Makes things messy. Do not use them if you can help it. And try to obey the K(eep) I(t) S(imple) S(tupid) rule.

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


How do I copy a 2 Dimensional array in Java?

/**
 * Clones the provided array
 * 
 * @param src
 * @return a new clone of the provided array
 */
public static int[][] cloneArray(int[][] src) {
    int length = src.length;
    int[][] target = new int[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}

Is it possible to modify this code to support n-dimensional arrays of Objects?

You would need to support arbitrary lengths of arrays and check if the src and destination have the same dimensions, and you would also need to copy each element of each array recursively, in case the Object was also an array.

It's been a while since I posted this, but I found a nice example of one way to create an n-dimensional array class. The class takes zero or more integers in the constructor, specifying the respective size of each dimension. The class uses an underlying flat array Object[] and calculates the index of each element using the dimensions and an array of multipliers. (This is how arrays are done in the C programming language.)

Copying an instance of NDimensionalArray would be as easy as copying any other 2D array, though you need to assert that each NDimensionalArray object has equal dimensions. This is probably the easiest way to do it, since there is no recursion, and this makes representation and access much simpler.

script to map network drive

Does this not work (assuming "ROUTERNAME" is the user name the router expects)?

net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"

Alternatively, you can use use a small VBScript:

Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")

l = "Z:"
s = "\\10.0.1.1\DRIVENAME"

u = "ROUTERNAME"
p = "PW"

Network.MapNetworkDrive l, s, False, u, p

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.

Best way to understand the difference between orElse() and orElseGet() is that orElse() will always be executed if the Optional<T> is null or not, But orElseGet() will only be executed when Optional<T> is null.

The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:

    Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
    String value = nonEmptyOptional.orElse(iAmStillExecuted());

    public static String iAmStillExecuted(){
    System.out.println("nonEmptyOptional is not NULL,still I am being executed");
    return "I got executed";
    }

Output: nonEmptyOptional is not NULL,still I am being executed


    Optional<String> emptyOptional = Optional.ofNullable(null);
    String value = emptyOptional.orElse(iAmStillExecuted());
    public static String iAmStillExecuted(){
    System.out.println("emptyOptional is NULL, I am being executed, it is normal as 
    per dictionary");
    return "I got executed";
    }

Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary

For orElseGet() , The method goes as per dictionary meaning, The orElseGet() part will be executed only when the Optional is null.

Benchmarks:

+--------------------+------+-----+------------+-------------+-------+
| Benchmark          | Mode | Cnt | Score      | Error       | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark    | avgt | 20  | 60934.425  | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20  | 3.798      | ± 0.030     | ns/op |
+--------------------+------+-----+------------+-------------+-------+

Remarks: orElseGet() has clearly outperformed orElse() for our particular example.

Hope it clears the doubts of people like me who wants the very basic ground example :)

How to check whether Kafka Server is running?

For Linux, "ps aux | grep kafka" see if kafka properties are shown in the results. E.g. /path/to/kafka/server.properties

Unresolved Import Issues with PyDev and Eclipse

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

My solution (for .net core 2.0) was that i had forgot to add the port number in the applicationUrl, under iisExpress in launchSettings.json

"iisExpress": {
  "applicationUrl": "https://localhost:50770",
  "sslPort": 50770
}

What is the difference between join and merge in Pandas?

  • Join: Default Index (If any same column name then it will throw an error in default mode because u have not defined lsuffix or rsuffix))
df_1.join(df_2)
  • Merge: Default Same Column Names (If no same column name it will throw an error in default mode)
df_1.merge(df_2)
  • on parameter has different meaning in both cases
df_1.merge(df_2, on='column_1')

df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')

Hide html horizontal but not vertical scrollbar

You can use css like this:

overflow-y: scroll;
overflow-x: hidden;

How to load an ImageView by URL in Android?

public class LoadWebImg extends Activity {

String image_URL=
 "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}
}

Vertically aligning a checkbox

Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.

Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):

input {
    width: 20px;

    position: relative;
    left: 200px;

    vertical-align: middle;
}

label {  
    width: 200px;

    position: relative;
    left: -20px;

    display: inline-block;
    vertical-align: middle;
}

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" /> seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

"The system cannot find the file specified"

I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.

How to link to a named anchor in Multimarkdown?

In standard Markdown, place an anchor <a name="abcd"></a> where you want to link to and refer to it on the same page by [link text](#abcd).

(This uses name= and not id=, for reasons explained in this answer.)

Remote references can use [link text](http://...#abcd) of course.

This works like a dream, provided you have control over the source and target texts. The anchor can even appear in a heading, thus:

### <a name="head1234"></a>A Heading in this SO entry!

produces:

A Heading in this SO entry!

and we can even link to it so:

and we can even [link](#head1234) to it so:

(On SO, the link doesn't work because the anchor is stripped.)

How to give environmental variable path for file appender in configuration file in log4j

This syntax is documented only in log4j 2.X so make sure you are using the correct version.

    <Appenders>
    <File name="file" fileName="${env:LOG_PATH}">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
        </PatternLayout>
    </File>
</Appenders>

http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup

Print series of prime numbers in python

Using filter function.

l=range(1,101)
for i in range(2,10): # for i in range(x,y), here y should be around or <= sqrt(101)
    l = filter(lambda x: x==i or x%i, l)

print l

No generated R.java file in my project

Here's another one: I was just about to cry, but managed to get my beloved R.java back:

I hadn't updated anything in my Android installation for quite a while. I needed a feature and ran the SDK Manager. Besides what I needed I basically checked everything it wanted to update. Afterwards my R.java disappeared in Eclipse.

To make it short, in the SDK Manager there was a new entry "Android SDK Build-tools" that I guess wasn't there the last time I had updated. It's kind of an obvious name, really. After I installed that one Eclipse gave me my R.java back.

Count all duplicates of each value

You'd want the COUNT operator.

SELECT NUMBER, COUNT(*) 
FROM T_NAME
GROUP BY NUMBER
ORDER BY NUMBER ASC

How do I show my global Git configuration?

To find all configurations, you just write this command:

git config --list

In my local i run this command .

Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f

WCF, Service attribute value in the ServiceHost directive could not be found

If you have renamed anything verify the (Properties/) AssemblyInfo.cs is correct, as well as the header in the service file.

ServiceName.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Company.Namespace.WcfApp" CodeBehind="WcfApp.svc.cs" %>

Aligning with your namespace in your Service.svc.cs

Postgresql column reference "id" is ambiguous

I suppose your p2vg table has also an id field , in that case , postgres cannot find if the id in the SELECT refers to vg or p2vg.

you should use SELECT(vg.id,vg.name) to remove ambiguity

SMTP error 554

Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.

The response content cannot be parsed because the Internet Explorer engine is not available, or

You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2

After this, WebClient will work without problems

Prefer composition over inheritance?

When you have an is-a relation between two classes (example dog is a canine), you go for inheritance.

On the other hand when you have has-a or some adjective relationship between two classes (student has courses) or (teacher studies courses), you chose composition.