Programs & Examples On #Jsx

JSX is an open source programming language, or an AltJS with classes and static types. The source code is compiled into JavaScript which is highly optimized. For questions about React, use [react-jsx] instead!

TypeScript and React - children type?

From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471

The recommended practice is to write the props type as {children?: any}

That worked for me. The child node can be many different things, so explicit typing can miss cases.

There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.

expected assignment or function call: no-unused-expressions ReactJS

The error - "Expected an assignment or function call and instead saw an expression no-unused-expressions" comes when we use curly braces i.e {} to return an object literal expression. In such case we can fix it with 2 options

  1. Use the parentheses i.e ()
  2. Use return statement with curly braces i.e {}

Example :

const items = ["Test1", "Test2", "Test3", "Test4"];
console.log(articles.map(item => { `this is ${item}` })); // wrong
console.log(items.map(item => (`this is ${item}`))); // Option1
console.log(items.map(item => { return `this is ${item}` })); // Option2

Loop inside React JSX

Array.from is the best way. If you want to create an array of JSX with some length.

function App() {
  return (
    <tbody>
      {Array.from({ length: 10 }, (_, key) => (
        <ObjectRow {...{ key }} />
      ))}
    </tbody>
  );
}

The above example is for when you do not have an array, so if you have an array you should map it in JSX like this:

function App() {
  return (
    <tbody>
      {list.map((item, key) => (
        <ObjectRow {...{ key }} />
      ))}
    </tbody>
  );
}

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

You should not use <Link> outside a <Router>

Write router in place of Main in render (last line in the code). Like this ReactDOM.render(router, document.getElementById('root'));

ReactJS - .JS vs .JSX

As already mentioned, there is no difference, if you create a file with .jsx or .js.

I would like to bring another expect of creating the files as .jsx while creating a component.

This is not mandatory, but an architectural approach that we can follow. So, in large projects we divide our components as Presentational components or Container components. Just to brief, in container components we write the logic to get data for the component and render the Presentational component with props. In presentational components, we usually donot write functional logic, presentational components are used to represent the UI with required props.

So, if you check the definition on JSX in React documents.

It says,

const element = <h1>Hello, world!</h1>;

It is called JSX, and it is a syntax extension to JavaScript. 
We recommend using it with React to describe what the UI should look like. 
JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. Instead of artificially separating technologies by putting
markup and logic in separate files, React separates concerns with loosely coupled units 
called “components” that contain both. 

React doesn’t require using JSX, but most people find it helpful as a visual aid when 
working with UI inside the JavaScript code. It also allows React to show more useful 
error and warning messages.

It means, It's not mandatory but you can think of creating presentational components with '.jsx' as it actually binds the props with the UI. and container components, as .js files as those contains logic to get the data.

It's a convention that you can follow while creating the .jsx or .js files, to logically and physically separate the code.

React-Native Button style not work

The React Native Button is very limited in what you can do, see; Button

It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />

If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity They are really easy to use :-)

React Native - Image Require Module using Dynamic Names

First, create a file with image required - React native images must be loaded this way.

assets/index.js

export const friendsandfoe = require('./friends-and-foe.png'); 
export const lifeanddeath = require('./life-and-death.png'); 
export const homeandgarden = require('./home-and-garden.png');

Now import all your assets

App.js

import * as All  from '../../assets';

You can now use your image as an interpolated value where imageValue (coming in from backend) is the same as named local file ie: 'homeandgarden':

<Image style={styles.image} source={All[`${imageValue}`]}></Image>

How to Call a Function inside a Render in React/Jsx

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  buttonClick(){_x000D_
    console.log("came here")_x000D_
    _x000D_
  }_x000D_
  _x000D_
  subComponent() {_x000D_
    return (<div>Hello World</div>);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div className="patient-container">_x000D_
          <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
          {this.subComponent()}_x000D_
       </div>_x000D_
     )_x000D_
  }_x000D_
  _x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

React.js: Identifying different inputs with one onChange handler

You can also do it like this:

...
constructor() {
    super();
    this.state = { input1: 0, input2: 0 };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(input, value) {
    this.setState({
        [input]: value
    })
}

render() {
    const total = this.state.input1 + this.state.input2;
    return (
        <div>
            {total}<br />
            <input type="text" onChange={e => this.handleChange('input1', e.target.value)} />
            <input type="text" onChange={e => this.handleChange('input2', e.target.value)} />
        </div>
    )
}

Render HTML string as real HTML in a React component

You can also use parseReactHTMLComponent from Jumper Package. Just look at it, it's easy and you don't need to use JSX syntax.

https://codesandbox.io/s/jumper-module-react-simple-parser-3b8c9?file=/src/App.js .

More on Jumper:

https://github.com/Grano22/jumper/blob/master/components.js

NPM Package:

https://www.npmjs.com/package/jumper_react

ReactJs: What should the PropTypes be for this.props.children?

If you want to include render prop components:

  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
    PropTypes.func
  ])

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

How to use componentWillMount() in React Hooks?

This is the way how I simulate constructor in functional components using the useRef hook:

function Component(props) {
    const willMount = useRef(true);
    if (willMount.current) {
        console.log('This runs only once before rendering the component.');
        willMount.current = false;        
    }

    return (<h1>Meow world!</h1>);
}

Here is the lifecycle example:

function RenderLog(props) {
    console.log('Render log: ' + props.children);
    return (<>{props.children}</>);
}

function Component(props) {

    console.log('Body');
    const [count, setCount] = useState(0);
    const willMount = useRef(true);

    if (willMount.current) {
        console.log('First time load (it runs only once)');
        setCount(2);
        willMount.current = false;
    } else {
        console.log('Repeated load');
    }

    useEffect(() => {
        console.log('Component did mount (it runs only once)');
        return () => console.log('Component will unmount');
    }, []);

    useEffect(() => {
        console.log('Component did update');
    });

    useEffect(() => {
        console.log('Component will receive props');
    }, [count]);


    return (
        <>
        <h1>{count}</h1>
        <RenderLog>{count}</RenderLog>
        </>
    );
}
[Log] Body
[Log] First time load (it runs only once)
[Log] Body
[Log] Repeated load
[Log] Render log: 2
[Log] Component did mount (it runs only once)
[Log] Component did update
[Log] Component will receive props

Of course Class components don't have Body steps, it's not possible to make 1:1 simulation due to different concepts of functions and classes.

React: Expected an assignment or function call and instead saw an expression

You must return something

instead of this (this is not the right way)

const def = (props) => { <div></div> };

try

const def = (props) => ( <div></div> );

or use return statement

const def = (props) => { return  <div></div> };

ReactJS map through Object

Do you get an error when you try to map through the object keys, or does it throw something else.

Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input" key={i}>
     <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>
))}

You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.

Android Lint contentDescription warning

Non textual widgets need a content description in some ways to describe textually the image so that screens readers to be able to describe the user interface. You can ignore the property xmlns:tools="http://schemas.android.com/tools"
tools:ignore="contentDescription"
or define the property android:contentDescription="your description"

Hibernate error: ids for this class must be manually assigned before calling save():

Resolved this problem using a Sequence ID defined in Oracle database.

ORACLE_DB_SEQ_ID is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.

@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Use:

string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));

Preventing SQL injection in Node.js

The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.

How to check if std::map contains a key without doing insert?

Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

Alternately my_map.find( key ) != my_map.end() works too.

Inline comments for Bash?

How about storing it in a variable?

#extraargs=-F
ls -l $extraargs -a /etc

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.

Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.

Then your HTML. I took the liberty to correct that too

<html>
    <head>
        <title> Delegate edit form</title>
    </head>

    <body>
          <p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";

mysql_connect($host,$usernm,$passwd); 
mysql_select_db($database);

$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){     // here too, you put a space between it
    $Name=$row['Name'];
    $Username=$row['User_name'];
    $Password=$row['User_password'];
    }
?>

Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)

Anyway, welcome to Stack Overflow

Interface/enum listing standard mime-type constants

Guava library

We have a Guava class for this: com.google.common.net.MediaType.

It was released with Guava 12 as stated in the source code and in Issue 823. Sources are available, too.

How do I declare a namespace in JavaScript?

JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollute the global namespace. Let's take an example of defining two functions without any namespace,

function func1() {
    console.log("This is a first definition");

}
function func1() {
    console.log("This is a second definition");
}
func1(); // This is a second definition

It always calls the second function definition. In this case, namespace will solve the name collision problem.

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

WHERE MyColumn = COALESCE(@value,MyColumn) 
  • If @value is NULL, it will compare MyColumn to itself, ignoring @value = no where clause.

  • IF @value has a value (NOT NULL) it will compare MyColumn to @value.

Reference: COALESCE (Transact-SQL).

Sleep function in C++

Recently I was learning about chrono library and thought of implementing a sleep function on my own. Here is the code,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

We can use it with any std::chrono::duration type (By default it takes std::chrono::seconds as argument). For example,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

using namespace std::chrono_literals;
int main (void) {
    std::chrono::steady_clock::time_point start1 = std::chrono::steady_clock::now();
    
    sleep(5s);  // sleep for 5 seconds
    
    std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();
    
    std::cout << std::setprecision(9) << std::fixed;
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::seconds>(end1-start1).count() << "s\n";
    
    std::chrono::steady_clock::time_point start2 = std::chrono::steady_clock::now();

    sleep(500000ns);  // sleep for 500000 nano seconds/500 micro seconds
    // same as writing: sleep(500us)
    
    std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();
    
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count() << "us\n";
    return 0;
}

For more information, visit https://en.cppreference.com/w/cpp/header/chrono and see this cppcon talk of Howard Hinnant, https://www.youtube.com/watch?v=P32hvk8b13M. He has two more talks on chrono library. And you can always use the library function, std::this_thread::sleep_for

Note: Outputs may not be accurate. So, don't expect it to give exact timings.

Android: making a fullscreen application

you can do make App in FullScreen Mode form just one line code. i am using this in my code.

just set AppTheme -> Theme.AppCompat.Light.NoActionBar in your style.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

It will work in all pages..

Can I set up HTML/Email Templates with ASP.NET?

You might also want to try loading a control, and then rendering it to a string and setting that as the HTML Body:

// Declare stringbuilder to render control to
StringBuilder sb = new StringBuilder();

// Load the control
UserControl ctrl = (UserControl) LoadControl("~/Controls/UserControl.ascx");

// Do stuff with ctrl here

// Render the control into the stringbuilder
StringWriter sw = new StringWriter(sb);
Html32TextWriter htw = new Html32TextWriter(sw);
ctrl.RenderControl(htw);

// Get full body text
string body = sb.ToString();

You could then construct your email as usual:

MailMessage message = new MailMessage();
message.From = new MailAddress("[email protected]", "from name");
message.Subject = "Email Subject";
message.Body = body;
message.BodyEncoding = Encoding.ASCII;
message.IsBodyHtml = true;

SmtpClient smtp = new SmtpClient("server");
smtp.Send(message);

You user control could contain other controls, such as a header and footer, and also take advantage of functionality such as data binding.

Eclipse Problems View not showing Errors anymore

If "Debug" has been recently activated then check the top right of the program (under the Minimise button) and click back onto Java.

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

REST HTTP status codes for failed validation or invalid duplicate

For input validation failure: 400 Bad Request + your optional description. This is suggested in the book "RESTful Web Services". For double submit: 409 Conflict


Update June 2014

The relevant specification used to be RFC2616, which gave the use of 400 (Bad Request) rather narrowly as

The request could not be understood by the server due to malformed syntax

So it might have been argued that it was inappropriate for semantic errors. But not any more; since June 2014 the relevant standard RFC 7231, which supersedes the previous RFC2616, gives the use of 400 (Bad Request) more broadly as

the server cannot or will not process the request due to something that is perceived to be a client error

Assign keyboard shortcut to run procedure

I ran into this problem myself. The only solution I have is to record the macro in an excel workbook first. Then, drag and drop THE MODULE from the open workbook into the add-in modules. This will be a copy of the above module, but the keyboard shortcut you assigned to it will thankfully persist.

I just record a garbage macro and move it in there, then copy the code from my real module afterwords.

Felt so great to figure this out, I felt like I had to reply to the 5 year old posts I found on the subject!!!

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

Multi-Line Comments in Ruby?

=begin
(some code here)
=end

and

# This code
# on multiple lines
# is commented out

are both correct. The advantage of the first type of comment is editability—it's easier to uncomment because fewer characters are deleted. The advantage of the second type of comment is readability—reading the code line by line, it's much easier to tell that a particular line has been commented out. Your call but think about who's coming after you and how easy it is for them to read and maintain.

IPython/Jupyter Problems saving notebook as PDF

This problem was experienced with both Ubuntu and Mac OSX. After a frantic set of searches and trials, both of them were solved. This requires both tex and pandoc; both jumbo external programs cannot installed by Python's pip.

Mac OSX: using MacPorts installation of pandoc

port install pandoc

This should take nearly an hour to complete (in the usual case). If the problem persists, you might have to install MacTeX distro. of TeXLive.

For Ubuntu: install vanilla TeXLive from the network installer -- not through apt-get. Then install pandoc using apt-get.

sudo apt-get install pandoc

A complete installation of TeXLive would require a upto to 4.4 GB on disk.

To save all this trouble, the recommeded way to use IPython/Jupyter Notebook would be to install Anaconda Python distribution.

Uncaught TypeError: Cannot read property 'value' of undefined

Try this, It always works, and you will get NO TypeError:

try{

    var i1 = document.getElementById('i1');
    var i2 = document.getElementById('i2');
    var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
    if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
    if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }

}catch(e){
    if(e){
    // If fails, Do something else
    }
}

Go Back to Previous Page

You specifically asked for JS solutions, but in the event that someone visits your form with JS disabled a PHP backup is always nice:

when the form loads grab the previous page address via something like $previous = $_SERVER['HTTP_REFERER']; and then set that as a <input type="hidden" value="$previous" /> in your form. When you process your form with the script you can grab that value and stick it in the header("Location:___") or stick the address directly into a link to send them back where they came from

No JS, pretty simple, and you can structure it so that it's only handled if the client doesn't have JS enabled.

How do I convert from BLOB to TEXT in MySQL?

phpMyAdmin screenshot Using phpMyAdmin you can also set the options to show BLOB content and show complete text.

open failed: EACCES (Permission denied)

If the clients are using Android 6.0, Android added new permission model for (Marshmallow).

Trick: If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

SQL: how to use UNION and order by a specific select?

SELECT id, 1 AS sort_order
  FROM b
UNION
SELECT id, 2 AS sort_order
  FROM a
MINUS
SELECT id, 2 AS sort_order
  FROM b
ORDER BY 2;

How to convert JSON to a Ruby hash

Have you tried: http://flori.github.com/json/?

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

what is the difference between XSD and WSDL

XSD is to validate the document, and contains metadata about the XML whereas WSDL is to describe the webservice location and operations.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

INSERT INTO dues_storage
SELECT field1, field2, ..., fieldN, CURRENT_DATE()
FROM dues
WHERE id = 5;

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

Bold & Non-Bold Text In A Single UILabel?

There's category based on bbrame's category. It works similar, but allows you boldify same UILabel multiple times with cumulative results.

UILabel+Boldify.h

@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end

UILabel+Boldify.m

@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}

- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
@end

With this corrections you may use it multiple times, eg:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];

will result with: "Updated: 2012/10/14 21:59 PM".

LINQ extension methods - Any() vs. Where() vs. Exists()

context.Authors.Where(a => a.Books.Any(b => b.BookID == bookID)).ToList();

a.Books is the list of books by that author. The property is automatically created by Linq-to-Sql, provided you have a foreign-key relationship set up.

So, a.Books.Any(b => b.BookID == bookID) translates to "Do any of the books by this author have an ID of bookID", which makes the complete expression "Who are the authors of the book with id bookID?"

That could also be written something like

  from a in context.Authors
  join b in context.Books on a.AuthorId equal b.AuthorID
  where b.BookID == bookID
  select a;

UPDATE: Any() as far as I know, only returns a bool. Its effective implementation is:

 public Any(this IEnumerable<T> coll, Func<T, bool> predicate)
 {
     foreach(T t in coll)
     {
         if (predicte(t))
            return true;
     }
     return false;
 }

Conda command not found

Sometimes, if you don't restart your terminal after you have installed anaconda also, it gives this error.

Close your terminal window and restart it.

It worked for me now!

Bind TextBox on Enter-key press

This works for me:

        <TextBox                 
            Text="{Binding Path=UserInput, UpdateSourceTrigger=PropertyChanged}">
            <TextBox.InputBindings>
                <KeyBinding Key="Return" 
                            Command="{Binding Ok}"/>
            </TextBox.InputBindings>
        </TextBox>

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

How do I get the current time zone of MySQL?

To get Current timezone of the mysql you can do following things:

 SELECT @@system_time_zone;   # from this you can get the system timezone 
 SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) # This will give you time zone if system timezone is different from global timezone

Now if you want to change the mysql timezone then:

 SET GLOBAL time_zone = '+00:00';   # this will set mysql timezone in UTC
 SET @@session.time_zone = "+00:00";  # by this you can chnage the timezone only for your particular session 

error: expected class-name before ‘{’ token

This should be a comment, but comments don't allow multi-line code.

Here's what's happening:

in Event.cpp

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

it isn't defined yet, so keep going

#define EVENT_H_
#include "common.h"

common.h gets processed ok

#include "Item.h"

Item.h gets processed ok

#include "Flight.h"

Flight.h gets processed ok

#include "Landing.h"

preprocessor starts processing Landing.h

#ifndef LANDING_H_

not defined yet, keep going

#define LANDING_H_

#include "Event.h"

preprocessor starts processing Event.h

#ifndef EVENT_H_

This IS defined already, the whole rest of the file gets skipped. Continuing with Landing.h

class Landing: public Event {

The preprocessor doesn't care about this, but the compiler goes "WTH is Event? I haven't heard about Event yet."

What are the benefits to marking a field as `readonly` in C#?

To put it in very practical terms:

If you use a const in dll A and dll B references that const, the value of that const will be compiled into dll B. If you redeploy dll A with a new value for that const, dll B will still be using the original value.

If you use a readonly in dll A and dll B references that readonly, that readonly will always be looked up at runtime. This means if you redeploy dll A with a new value for that readonly, dll B will use that new value.

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

Right way to split an std::string into a vector<string>

vector<string> split(string str, string token){
    vector<string>result;
    while(str.size()){
        int index = str.find(token);
        if(index!=string::npos){
            result.push_back(str.substr(0,index));
            str = str.substr(index+token.size());
            if(str.size()==0)result.push_back(str);
        }else{
            result.push_back(str);
            str = "";
        }
    }
    return result;
}

split("1,2,3",",") ==> ["1","2","3"]

split("1,2,",",") ==> ["1","2",""]

split("1token2token3","token") ==> ["1","2","3"]

How to define two angular apps / modules in one page?

Manual bootstrapping both the modules will work. Look at this

  <!-- IN HTML -->
  <div id="dvFirst">
    <div ng-controller="FirstController">
      <p>1: {{ desc }}</p>
    </div>
  </div>

  <div id="dvSecond">
    <div ng-controller="SecondController ">
      <p>2: {{ desc }}</p>
    </div>
  </div>



// IN SCRIPT       
var dvFirst = document.getElementById('dvFirst');
var dvSecond = document.getElementById('dvSecond');

angular.element(document).ready(function() {
   angular.bootstrap(dvFirst, ['firstApp']);
   angular.bootstrap(dvSecond, ['secondApp']);
});

Here is the link to the Plunker http://plnkr.co/edit/1SdZ4QpPfuHtdBjTKJIu?p=preview

NOTE: In html, there is no ng-app. id has been used instead.

How to set time to midnight for current day?

You can use the Date property of the DateTime object - eg

DateTime midnight = DateTime.Now.Date;

So your code example becomes

private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }

PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...

var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

Comparing two byte arrays in .NET

You can use Enumerable.SequenceEqual method.

using System;
using System.Linq;
...
var a1 = new int[] { 1, 2, 3};
var a2 = new int[] { 1, 2, 3};
var a3 = new int[] { 1, 2, 4};
var x = a1.SequenceEqual(a2); // true
var y = a1.SequenceEqual(a3); // false

If you can't use .NET 3.5 for some reason, your method is OK.
Compiler\run-time environment will optimize your loop so you don't need to worry about performance.

What is the idiomatic Go equivalent of C's ternary operator?

One-liners, though shunned by the creators, have their place.

This one solves the lazy evaluation problem by letting you, optionally, pass functions to be evaluated if necessary:

func FullTernary(e bool, a, b interface{}) interface{} {
    if e {
        if reflect.TypeOf(a).Kind() == reflect.Func {
            return a.(func() interface{})()
        }
        return a
    }
    if reflect.TypeOf(b).Kind() == reflect.Func {
        return b.(func() interface{})()
    }
    return b
}

func demo() {
    a := "hello"
    b := func() interface{} { return a + " world" }
    c := func() interface{} { return func() string { return "bye" } }
    fmt.Println(FullTernary(true, a, b).(string)) // cast shown, but not required
    fmt.Println(FullTernary(false, a, b))
    fmt.Println(FullTernary(true, b, a))
    fmt.Println(FullTernary(false, b, a))
    fmt.Println(FullTernary(true, c, nil).(func() string)())
}

Output

hello
hello world
hello world
hello
bye
  • Functions passed in must return an interface{} to satisfy the internal cast operation.
  • Depending on the context, you might choose to cast the output to a specific type.
  • If you wanted to return a function from this, you would need to wrap it as shown with c.

The standalone solution here is also nice, but could be less clear for some uses.

Correct way to write line to file?

I do not think there is a "correct" way.

I would use:

with open ('myfile', 'a') as f: f.write ('hi there\n')

In memoriam Tim Toady.

Select a date from date picker using Selenium webdriver

I think there will be different ways to select a Date for different Date picker formats. For a Date Picker where you need to select a year and month from a dropdown and then pick/click a Date, I wrote the following code.

private void setupDate(WebDriver driver, String csvRow) throws Exception {
    String date[] = (csvRow).split("-");
    driver.findElement(By.id("flddateanchor")).click();
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-year")))
            .selectByVisibleText(date[0]);
    Thread.sleep(1000);
    new Select(driver.findElement(By
            .cssSelector("select.ui-datepicker-month")))
            .selectByVisibleText(date[1]);
    Thread.sleep(1000);
    driver.findElement(By.linkText(date[2])).click();
    Thread.sleep(1000);
}

I got the cssSelector part by the Selenium Firefox IDE. Also, my Date(csvRow) is in (2015-03-31) format.

Hope it helps.

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

Vue.js toggle class on click

This answer relevant for Vue.js version 2

<th 
  class="initial " 
  v-on:click="myFilter"
  v-bind:class="{ active: isActive }"
>
  <span class="wkday">M</span>
</th>

The rest of the answer by Douglas is still applicable (setting up the new Vue instance with isActive: false, etc).

Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

TypeError: Converting circular structure to JSON in nodejs

JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.

The request (req) object is circular by nature - Node does that.

In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:

console.log("Request data:");
console.log(req);

How Big can a Python List Get?

There is no limitation of list number. The main reason which causes your error is the RAM. Please upgrade your memory size.

HashMaps and Null values?

HashMap supports both null keys and values

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

... and permits null values and the null key

So your problem is probably not the map itself.

Add centered text to the middle of a <hr/>-like line

If you can use CSS and are willing to use the deprecated align attribute, a styled fieldset/legend will work:

<style type="text/css">
fieldset { 
    border-width: 1px 0 0 0;
}
</style>

<fieldset>
<legend align="center">First Section</legend>
Section 1 Stuff
</fieldset>

<fieldset>
<legend align="center">Second Section</legend>
Section 2 Stuff
</fieldset>

The intended purpose of a fieldset is to logically group form fields. As willoler pointed out, a text-align: center style for will not work for legend elements. align="center" is deprecated HTML but it should center the text properly in all browsers.

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to implement a tree data-structure in Java?

What about this?

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
  * @author [email protected] (Yohann Coppel)
  * 
  * @param <T>
  *          Object's type in the tree.
*/
public class Tree<T> {

  private T head;

  private ArrayList<Tree<T>> leafs = new ArrayList<Tree<T>>();

  private Tree<T> parent = null;

  private HashMap<T, Tree<T>> locate = new HashMap<T, Tree<T>>();

  public Tree(T head) {
    this.head = head;
    locate.put(head, this);
  }

  public void addLeaf(T root, T leaf) {
    if (locate.containsKey(root)) {
      locate.get(root).addLeaf(leaf);
    } else {
      addLeaf(root).addLeaf(leaf);
    }
  }

  public Tree<T> addLeaf(T leaf) {
    Tree<T> t = new Tree<T>(leaf);
    leafs.add(t);
    t.parent = this;
    t.locate = this.locate;
    locate.put(leaf, t);
    return t;
  }

  public Tree<T> setAsParent(T parentRoot) {
    Tree<T> t = new Tree<T>(parentRoot);
    t.leafs.add(this);
    this.parent = t;
    t.locate = this.locate;
    t.locate.put(head, this);
    t.locate.put(parentRoot, t);
    return t;
  }

  public T getHead() {
    return head;
  }

  public Tree<T> getTree(T element) {
    return locate.get(element);
  }

  public Tree<T> getParent() {
    return parent;
  }

  public Collection<T> getSuccessors(T root) {
    Collection<T> successors = new ArrayList<T>();
    Tree<T> tree = getTree(root);
    if (null != tree) {
      for (Tree<T> leaf : tree.leafs) {
        successors.add(leaf.head);
      }
    }
    return successors;
  }

  public Collection<Tree<T>> getSubTrees() {
    return leafs;
  }

  public static <T> Collection<T> getSuccessors(T of, Collection<Tree<T>> in) {
    for (Tree<T> tree : in) {
      if (tree.locate.containsKey(of)) {
        return tree.getSuccessors(of);
      }
    }
    return new ArrayList<T>();
  }

  @Override
  public String toString() {
    return printTree(0);
  }

  private static final int indent = 2;

  private String printTree(int increment) {
    String s = "";
    String inc = "";
    for (int i = 0; i < increment; ++i) {
      inc = inc + " ";
    }
    s = inc + head;
    for (Tree<T> child : leafs) {
      s += "\n" + child.printTree(increment + indent);
    }
    return s;
  }
}

JavaScript dictionary with names

I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:

var myMappings = {
    "Name": 0.1,
    "Phone": 0.1,
    "Address": 0.5,
    "Zip": 0.1,
    "Comments": 0.2
};

for (var col in myMappings) {
    alert((myMappings[col] * 100) + "%");
}

Is it fine to have foreign key as primary key?

Yes, it is legal to have a primary key being a foreign key. This is a rare construct, but it applies for:

  • a 1:1 relation. The two tables cannot be merged in one because of different permissions and privileges only apply at table level (as of 2017, such a database would be odd).

  • a 1:0..1 relation. Profile may or may not exist, depending on the user type.

  • performance is an issue, and the design acts as a partition: the profile table is rarely accessed, hosted on a separate disk or has a different sharding policy as compared to the users table. Would not make sense if the underlining storage is columnar.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

To solve the problem in my case it was just missing this line

<tx:annotation-driven transaction-manager="myTxManager" />

in the application-context file.

The @Transactional annotation over a method was not taken into account.

Hope the answer will help someone

How can I do a BEFORE UPDATED trigger with sql server?

T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.

I believe you will want to use an INSTEAD OF trigger.

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

What does it mean to "program to an interface"?

A lot of explanation out there, but to make it even more simpler. Take for instance a List. One can implement a list with as:

  1. An internal array
  2. A linked list
  3. Other implementations

By building to an interface, say a List. You only code as to definition of List or what List means in reality.

You could use any type of implementation internally say an array implementation. But suppose you wish to change the implementation for some reason say a bug or performance. Then you just have to change the declaration List<String> ls = new ArrayList<String>() to List<String> ls = new LinkedList<String>().

Nowhere else in code, will you have to change anything else; Because everything else was built on the definition of List.

How to remove backslash on json_encode() function?

You do not want to delete it. Because JSON uses double quotes " " for strings, and your one returns

"$(\"#output\").append(\"
This is a test!<\/p>\")"

these backslashes escape these quotes

When to use virtual destructors?

Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:

class Base 
{
    // some virtual methods
};

class Derived : public Base
{
    ~Derived()
    {
        // Do some important cleanup
    }
};

Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:

Base *b = new Derived();
// use b
delete b; // Here's the problem!

Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour:

[In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.

To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically.

If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete on a base class pointer.

You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.

Appending a list to a list of lists in R

This answer is similar to the accepted one, but a bit less convoluted.

L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

Retrieve a Fragment from a ViewPager

I implemented this easy with a bit different approach.

My custom FragmentAdapter.getItem method returned not new MyFragment(), but the instance of MyFragment that was created in FragmentAdapter constructor.

In my activity I then got the fragment from the adapter, check if it is instanceOf needed Fragment, then cast and use needed methods.

Trim spaces from start and end of string

Here, this should do all that you need

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

PHP - check if variable is undefined

The isset() function does not check if a variable is defined.

It seems you've specifically stated that you're not looking for isset() in the question. I don't know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.

It's important to realize in programming that null is something. I don't know why it was decided that isset() would return false if the value is null.

To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars(). There is no equivalent to JavaScript's undefined (which is what was shown in the question, no jQuery being used there).

In the following example it will work the same way as JavaScript's undefined check.

$isset = isset($variable);
var_dump($isset); // false

But in this example, it won't work like JavaScript's undefined check.

$variable = null;
$isset = isset($variable);
var_dump($isset); // false

$variable is being defined as null, but the isset() call still fails.

So how do you actually check if a variable is defined? You check the defined variables.

Using get_defined_vars() will return an associative array with keys as variable names and values as the variable values. We still can't use isset(get_defined_vars()['variable']) here because the key could exist and the value still be null, so we have to use array_key_exists('variable', get_defined_vars()).

$variable = null;
$isset = array_key_exists('variable', get_defined_vars());
var_dump($isset); // true


$isset = array_key_exists('otherVariable', get_defined_vars());
var_dump($isset); // false

However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How to find a hash key containing a matching value

You can invert the hash. clients.invert["client_id"=>"2180"] returns "orange"

How to make for loops in Java increase by increments other than 1

It should be like this

for(int j = 0; j<=90; j += 3) 

but watch out for

for(int j = 0; j<=90; j =+ 3) 

or

for(int j = 0; j<=90; j = j + 3)

How to adjust an UIButton's imageSize?

You can also do that from inteface builder like this.

enter image description here

I think it's helpful.

How to initialise memory with new operator in C++?

There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...

Manual initialisation of all elements in loop

int* p = new int[10];
for (int i = 0; i < 10; i++)
    p[i] = 0;

Using std::memset function from <cstring>

int* p = new int[10];
std::memset(p, 0, sizeof *p * 10);

Using std::fill_n algorithm from <algorithm>

int* p = new int[10];
std::fill_n(p, 10, 0);

Using std::vector container

std::vector<int> v(10); // elements zero'ed

If C++11 is available, using initializer list features

int a[] = { 1, 2, 3 }; // 3-element static size array
vector<int> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime

How to change root logging level programmatically for logback

Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

jQuery ajax error function

          cache: false,
          url: "addInterview_Code.asp",
          type: "POST",
          datatype: "text",
          data: strData,
          success: function (html) {
              alert('successful : ' + html);
              $("#result").html("Successful");
          },
          error: function(data, errorThrown)
          {
              alert('request failed :'+errorThrown);
          }

Get element from within an iFrame

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

You could more simply write:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

and the first valid inner doc will be returned.

Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById...etc.)

IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

The program can't start because libgcc_s_dw2-1.dll is missing

See also. It solved my problem.

By the way, is it definitely compiler flag? Maybe linker is the more suitable term here?

How do you move a file?

Using TortoiseSVN I just right-click and drag the folder from one location to another. When you release the right-click you'll have the option to "SVN Move Version File." However, I believe that SVN doesn't do anything "fancy" there, but simply deletes the file in the previous location and Adds it to the new location.

Why does DEBUG=False setting make my django Static Files Access fail?

You can debug this in many different ways. Here's my approach.

localsettings.py:

DEBUG = False
DEBUG404 = True

urls.py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
         {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
    )

Be sure to read the docs ;)

https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

How can I have linebreaks in my long LaTeX equations?

If it is inline equation, then use \allowbreak. Use it like:

$x_1,x_2,x_3,\allowbreak x_4,x_5$.

Latex will break equation in this place only if necessary.

How do I move a file from one location to another in Java?

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. delete the source file

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

Creating a system overlay window (always on top)

This is an old Question but recently Android has a support for Bubbles. Bubbles are soon going to be launched but currently developers can start using them.They are designed to be an alternative to using SYSTEM_ALERT_WINDOW. Apps like (Facebook Messenger and MusiXMatch use the same concept).

Bubbles

Bubbles are created via the Notification API, you send your notification as normal. If you want it to bubble you need to attach some extra data to it. For more information about Bubbles you can go to the official Android Developer Guide on Bubbles.

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

Listing files in a directory matching a pattern in Java

Since java 7 you can the java.nio package to achieve the same result:

Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
    for (Path entry: stream) {
        files.add(entry.toFile());
    }
    return files;
} catch (IOException x) {
    throw new RuntimeException(String.format("error reading folder %s: %s",
    dir,
    x.getMessage()),
    x);
}

jQuery: Check if special characters exists in string

You are checking whether the string contains all illegal characters. Change the ||s to &&s.

How do I instantiate a Queue object in java?

Queue in Java is defined as an interface and many ready-to-use implementation is present as part of JDK release. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, ConcurrentLinkedQueue, Linked Transfer Queue, Synchronous Queue etc.

SO You can create any of these class and hold it as Queue reference. for example

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

 public static void main (String[] args) {
  Queue que = new LinkedList();
  que.add("first");
  que.offer("second");
  que.offer("third");
  System.out.println("Queue Print:: " + que);
  
  String head = que.element();
  System.out.println("Head element:: " + head);
  
  String element1 = que.poll();
  System.out.println("Removed Element:: " + element1);
  
  System.out.println("Queue Print after poll:: " + que);
  String element2 = que.remove();
  System.out.println("Removed Element:: " + element2);
  
  System.out.println("Queue Print after remove:: " + que);  
 }
}

You can also implement your own custom Queue implementing Queue interface.

Text Editor which shows \r\n?

I'd bet that Programmer's Notepad would give you something like that...

How to get WordPress post featured image URL

You can also get the URL for image attachments as follows. It works fine.

if (has_post_thumbnail()) {
    $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium'); 
}

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

//first: Create a class as your view model

public class EventViewModel 
{
 public int Id{get;set}
 public string Property1{get;set;}
 public string Property2{get;set;}
}
//then from your method
[HttpGet]
public async Task<ActionResult> GetEvent()
{
 var events = await db.Event.Find(x => x.ID != 0);
 List<EventViewModel> model = events.Select(event => new EventViewModel(){
 Id = event.Id,
 Property1 = event.Property1,
 Property1 = event.Property2
}).ToList();
 return Json(new{ data = model }, JsonRequestBehavior.AllowGet);
}

How do I POST urlencoded form data with $http without jQuery?

The problem is the JSON string format, You can use a simple URL string in data:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});

How to install a package inside virtualenv?

Sharing what has worked for me in both Ubuntu and Windows. This is for python3. To do for python2, replace "3" with "2":

Ubuntu

pip install virtualenv --user
virtualenv -p python3 /tmp/VIRTUAL
source /tmp/VIRTUAL/bin/activate
which python3

To install any package: pip install package

To get out of the virtual environment: deactivate

To activate again: source /tmp/VIRTUAL/bin/activate

Full explanation here.

Windows

(Assuming you have MiniConda installed and are in the Start Menu > Anaconda > Anaconda Terminal)

conda create -n VIRTUAL python=3  
activate VIRTUAL

To install any package: pip install package or conda install package

To get out of the virtual environment: deactivate

To activate again: activate VIRTUAL

Full explanation here.

Connect with SSH through a proxy

@rogerdpack for windows platform it is really hard to find a nc.exe with -X(http_proxy), however, I have found nc can be replaced by ncat, full example as follows:

Host github.com
     HostName github.com
         #ProxyCommand nc -X connect -x 127.0.0.1:1080 %h %p
         ProxyCommand ncat --proxy 127.0.0.1:1080 %h %p
     User git
     Port 22
     IdentityFile D:\Users\Administrator\.ssh\github_key

and ncat with --proxy can do a perfect work

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

Set a form's action attribute when submitting?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.

Something like this:

<form id="whatever" name="whatever" onSubmit="return xyz();">
    Here is your entire form
    <input type="submit">
</form>;

<script type=text/javascript>
function xyz() {
  document.getElementById('whatever').action = 'whatever you want'
}
</script>

Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

Getting value of select (dropdown) before change

keep the currently selected drop down value with chosen jquery in a global variable before writing the drop down 'on change' action function. If you want to set previous value in the function you can use the global variable.

//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
  function (result) {
  if (result) {
     return true;
  } else {
      $("#dropDownList").val(previousValue).trigger('chosen:updated');  
     return false;
         }
  });
});

SQL Query to fetch data from the last 30 days?

Try this : Using this you can select data from last 30 days

SELECT
    *
FROM
    product
WHERE
    purchase_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH)

To get total number of columns in a table in sql

This query gets the columns name

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

And this one gets the count

SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

How can I convert an HTML table to CSV?

Just to add to these answers (as i've recently been attempting a similar thing) - if Google spreadsheets is your spreadsheeting program of choice. Simply do these two things.

1. Strip everything out of your html file around the Table opening/closing tags and resave it as another html file.

2. Import that html file directly into google spreadsheets and you'll have your information beautifully imported (Top tip: if you used inline styles in your table, they will be imported as well!)

Saved me loads of time and figuring out different conversions.

Bootstrap 3 Gutter Size

@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:

.row {
    margin-left: -7px;
    margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
    padding-left: 7px;
    padding-right: 7px;
}
.container {
    padding-left: 14px;
    padding-right: 14px;
}

This leaves a 14px gutter and outside margin in all places.

How to convert array into comma separated string in javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

_x000D_
_x000D_
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
_x000D_
_x000D_

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

MySQL - Get row number on select

SELECT @rn:=@rn+1 AS rank, itemID, ordercount
FROM (
  SELECT itemID, COUNT(*) AS ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC
) t1, (SELECT @rn:=0) t2;

git pull aborted with error filename too long

Open your.gitconfig file to add the longpaths property. So it will look like the following:

[core]
symlinks = false
autocrlf = true
longpaths = true

How to retry after exception?

_x000D_
_x000D_
attempts = 3_x000D_
while attempts:_x000D_
  try:_x000D_
     ..._x000D_
     ..._x000D_
     <status ok>_x000D_
     break_x000D_
  except:_x000D_
    attempts -=1_x000D_
else: # executed only break was not  raised_x000D_
   <status failed>
_x000D_
_x000D_
_x000D_

CUDA incompatible with my gcc version

Another way of configuring nvcc to use a specific version of gcc (gcc-4.4, for instance), is to edit nvcc.profile and alter PATH to include the path to the gcc you want to use first.

For example (gcc-4.4.6 installed in /opt):

PATH += /opt/gcc-4.4.6/lib/gcc/x86_64-unknown-linux-gnu/4.4.6:/opt/gcc-4.4.6/bin:$(TOP)/open64/bin:$(TOP)/share/cuda/nvvm:$(_HERE_):

The location of nvcc.profile varies, but it should be in the same directory as the nvcc executable itself.

This is a bit of a hack, as nvcc.profile is not intended for user configuration as per the nvcc manual, but it was the solution which worked best for me.

Converting Hexadecimal String to Decimal Integer

void htod(String hexadecimal)
{
    int h = hexadecimal.length() - 1;
    int d = 0;
    int n = 0;

    for(int i = 0; i<hexadecimal.length(); i++)
    {
        char ch = hexadecimal.charAt(i);
        boolean flag = false;
        switch(ch)
        {
            case '1': n = 1; break;
            case '2': n = 2; break;
            case '3': n = 3; break;
            case '4': n = 4; break;
            case '5': n = 5; break;
            case '6': n = 6; break;
            case '7': n = 7; break;
            case '8': n = 8; break;
            case '9': n = 9; break;
            case 'A': n = 10; break;
            case 'B': n = 11; break;
            case 'C': n = 12; break;
            case 'D': n = 13; break;
            case 'E': n = 14; break;
            case 'F': n = 15; break;
            default : flag = true;
        }
        if(flag)
        {
            System.out.println("Wrong Entry"); 
            break;
        }
        d = (int)(n*(Math.pow(16,h))) + (int)d;
        h--;
    }
    System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}

PHP header redirect 301 - what are the implications?

This is better:

<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

Axios handling errors

If you want to gain access to the whole the error body, do it as shown below:

 async function login(reqBody) {
  try {
    let res = await Axios({
      method: 'post',
      url: 'https://myApi.com/path/to/endpoint',
      data: reqBody
    });

    let data = res.data;
    return data;
  } catch (error) {
    console.log(error.response); // this is the main part. Use the response property from the error object

    return error.response;
  }

}

Function or sub to add new row and data to table

Minor variation on Geoff's answer.

New Data in Array:

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

New Data in Horizontal Range:

Sub AddDataRow(tableName As String, NewData As Range)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last table row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Copy NewData to new table record
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    lastRow.Value = NewData.Value
End Sub

Access props inside quotes in React JSX

If you want to use the es6 template literals, you need braces around the tick marks as well:

<img className="image" src={`images/${this.props.image}`} />

Is it possible to log all HTTP request headers with Apache?

mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.

Here is how to use it.

LoadModule log_forensic_module /usr/lib64/httpd/modules/mod_log_forensic.so 
<IfModule log_forensic_module> 
ForensicLog /var/log/httpd/forensic_log 
</IfModule> 

Correlation between two vectors?

To perform a linear regression between two vectors x and y follow these steps:

[p,err] = polyfit(x,y,1);   % First order polynomial
y_fit = polyval(p,x,err);   % Values on a line
y_dif = y - y_fit;          % y value difference (residuals)
SSdif = sum(y_dif.^2);      % Sum square of difference
SStot = (length(y)-1)*var(y);   % Sum square of y taken from variance
rsq = 1-SSdif/SStot;        % Correlation 'r' value. If 1.0 the correlelation is perfect

For x=[10;200;7;150] and y=[0.001;0.45;0.0007;0.2] I get rsq = 0.9181.

Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html

C# convert int to string with padding zeros?

i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers
i.ToString("0000"); - explicit form
i.ToString("D4"); - short form format specifier
$"{i:0000}"; - string interpolation (C# 6.0+)

How to import a SQL Server .bak file into MySQL?

I did not manage to find a way to do it directly.

Instead I imported the bak file into SQL Server 2008 Express, and then used MySQL Migration Toolkit.

Worked like a charm!

How to pick a new color for each plotted line within a figure in matplotlib?

I usually use the second one of these:

from matplotlib.pyplot import cm
import numpy as np

#variable n below should be number of curves to plot

#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   plt.plot(x, y,c=c)

#or version 2:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   plt.plot(x, y,c=c)

Example of 2: example plot with iter,next color

How to set up Automapper in ASP.NET Core

services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)

After configuring as below

   var config = new AutoMapper.MapperConfiguration(cfg =>
   {                 
       cfg.CreateMap<ClientCustomer, Models.Customer>();
   });

initialize the mapper IMapper mapper = config.CreateMapper();

and add the mapper object to services as a singleton services.AddSingleton(mapper);

this way I am able to add a DI to controller

  private IMapper autoMapper = null;

  public VerifyController(IMapper mapper)
  {              
   autoMapper = mapper;  
  }

and I have used as below in my action methods

  ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

The APK file does not exist on disk

I've solved building an apk using the Build option from the top window and Build APK. No need to do something weird.

How do I inject a controller into another controller in AngularJS

If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

For example:

//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
  ...,
  controller : function WizardController() {
    this.disableNext = function() { 
      //disable next step... some implementation to disable the next button hosted by the wizard
    }
  },
  ...
});

//some child component
myModule.component('onboardingStep', {
 ...,
 controller : function OnboadingStepController(){

    this.$onInit = function() {
      //.... you can access this.container.disableNext() function
    }

    this.onChange = function(val) {
      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
      if(notIsValid(val)){
        this.container.disableNext();
      }
    }
 },
 ...,
 require : {
    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
 },
 ...
});

Now the usage of these above components might be something like this:

<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->

<on-boarding-step ...>
 <!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>

There are many ways you can set up require.

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

? - Attempt to locate the required controller or pass null to the link fn if not found.

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.



Old Answer:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

Example:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
   //In this case it is the child scope of this scope.
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {
    this.myMethod = function () {
        $log.debug("TestCtrl1 - myMethod");
    }
}]);

and while consuming do:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
     var testCtrl1ViewModel = $controller('TestCtrl1');
     testCtrl1ViewModel.myMethod();
}]);

In the first case really the $scope is your view model, and in the second case it the controller instance itself.

Load a HTML page within another HTML page

<button onclick="window.open('http://www.google.com');">Open popup</button>

How to run the Python program forever?

Yes, you can use a while True: loop that never breaks to run Python code continually.

However, you will need to put the code you want to run continually inside the loop:

#!/usr/bin/python

while True:
    # some python code that I want 
    # to keep on running

Also, time.sleep is used to suspend the operation of a script for a period of time. So, since you want yours to run continually, I don't see why you would use it.

Convert Little Endian to Big Endian

I am assuming you are on linux

Include "byteswap.h" & Use int32_t bswap_32(int32_t argument);

It is logical view, In actual see, /usr/include/byteswap.h

deleting rows in numpy array

Here's a one liner (yes, it is similar to user333700's, but a little more straightforward):

>>> import numpy as np
>>> arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], 
                [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
>>> print arr[arr.all(1)]
array([[ 0.96488889,  0.73641667,  0.67521429,  0.592875  ,  0.53172222]])

By the way, this method is much, much faster than the masked array method for large matrices. For a 2048 x 5 matrix, this method is about 1000x faster.

By the way, user333700's method (from his comment) was slightly faster in my tests, though it boggles my mind why.

HTTPS using Jersey Client

Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :

System.setProperty("jsse.enableSNIExtension", "false");

(Courtesy to many stackoverflow answers combined together to figure this out)

The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
    public static ClientConfig configureClient()
    {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] certs = new TrustManager[]
        {
            new X509TrustManager()
            {
                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }
            }
        };
        SSLContext ctx = null;
        try
        {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        }
        catch (java.security.GeneralSecurityException ex)
        {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        ClientConfig config = new DefaultClientConfig();
        try
        {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
                    new HostnameVerifier()
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            },
                    ctx));
        }
        catch (Exception e)
        {
        }
        return config;
    }

    public static Client createClient()
    {
        return Client.create(ClientHelper.configureClient());
    }

gpg decryption fails with no secret key error

This error will arise when using the utility pass if the terminal window is too small!

Just make the terminal window a few lines taller.

Very confusing.

How do I redirect to the previous action in ASP.NET MVC?

If you are not concerned with unit testing then you can simply write:

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());

Inserting HTML elements with JavaScript

You want this

document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );

Format number as percent in MS SQL Server

SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'

RESULT:  0.97 %

xxxxxx.exe is not a valid Win32 application

While seleted answer was right time ago, and then noelicus gave correct update regarding v110_xp platform toolset, there is still one more issue that could produse this behaviour.

A note about issue was already posted by mahesh in his comment, and I would like to highlight this as I have spend couple of days struggling and then find it by myself.

So, if you have a blank in "Configuration Properties -> Linker -> System -> Subsystem" you will still get the "not valid Win32 app" error on XP and Win2003 while on Win7 it works without this annoying error. The error gone as soon as I've put subsystem:console.

How to prevent a browser from storing passwords

I needed this a couple of years ago for a specific situation: Two people who know their network passwords access the same machine at the same time to sign a legal agreement.

You don't want either password saved in that situation because saving a password is a legal issue, not a technical one where both the physical and temporal presence of both individuals is mandatory. Now, I'll agree that this is a rare situation to encounter, but such situations do exist and built-in password managers in web browsers are unhelpful.

My technical solution to the above was to swap between password and text types and make the background color match the text color when the field is a plain text field (thereby continuing to hide the password). Browsers don't ask to save passwords that are stored in plain text fields.

jQuery plugin:

https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js

Relevant source code from the above link:

(function($) {
$.fn.StopPasswordManager = function() {
    return this.each(function() {
        var $this = $(this);

        $this.addClass('no-print');
        $this.attr('data-background-color', $this.css('background-color'));
        $this.css('background-color', $this.css('color'));
        $this.attr('type', 'text');
        $this.attr('autocomplete', 'off');

        $this.focus(function() {
            $this.attr('type', 'password');
            $this.css('background-color', $this.attr('data-background-color'));
        });

        $this.blur(function() {
            $this.css('background-color', $this.css('color'));
            $this.attr('type', 'text');
            $this[0].selectionStart = $this[0].selectionEnd;
        });

        $this.on('keydown', function(e) {
            if (e.keyCode == 13)
            {
                $this.css('background-color', $this.css('color'));
                $this.attr('type', 'text');
                $this[0].selectionStart = $this[0].selectionEnd;
            }
        });
    });
}
}(jQuery));

Demo:

https://barebonescms.com/demos/admin_pack/admin.php

Click "Add Entry" in the menu and then scroll to the bottom of the page to "Module: Stop Password Manager".

iPhone Debugging: How to resolve 'failed to get the task for process'?

I just changed my bundleIdentifier name, that seemed to do the trick.

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Cycles in family tree software

Potential legal implications aside, it certainly seems that you need to treat a 'node' on a family tree as a predecessor-person rather than assuming that the node can be the-one-and-only person.

Have the tree node include a person as well as the successors - and then you can have another node deeper down the tree that includes the same person with different successors.

How to limit the maximum files chosen when using multiple file input

On change of the input track how many files are selected:

_x000D_
_x000D_
$("#image").on("change", function() {_x000D_
    if ($("#image")[0].files.length > 2) {_x000D_
        alert("You can select only 2 images");_x000D_
    } else {_x000D_
        $("#imageUploadForm").submit();_x000D_
    }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<strong>On change of the input track how many files are selected:</strong>_x000D_
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
_x000D_
_x000D_
_x000D_

Build fat static library (device + simulator) using Xcode and SDK 4+

I needed a fat static lib for JsonKit so created a static lib project in Xcode and then ran this bash script in the project directory. So long as you've configured the xcode project with "Build active configuration only" turned off, you should get all architectures in one lib.

#!/bin/bash
xcodebuild -sdk iphoneos
xcodebuild -sdk iphonesimulator
lipo -create -output libJsonKit.a build/Release-iphoneos/libJsonKit.a build/Release-iphonesimulator/libJsonKit.a

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Tainted canvases may not be exported

If you're using ctx.drawImage() function, you can do the following:

var img = loadImage('../yourimage.png', callback);

function loadImage(src, callback) {
    var img = new Image();

    img.onload = callback;
    img.setAttribute('crossorigin', 'anonymous'); // works for me

    img.src = src;

    return img;
}

And in your callback you can now use ctx.drawImage and export it using toDataURL

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I was also getting the same error and it simply got resolved after installing the MS offices driver and Execute the job in 32 Bit DTEXEC. Now it works fine.

You can get the setup from below.

https://www.microsoft.com/en-in/download/confirmation.aspx?id=23734

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

In addition to the accepted answer, there's a third option that can be useful in some cases:

v1 with random MAC ("v1mc")

You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.

First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:

from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes  # py3 only

def uuid1mc():
    # NOTE: The constant here is required by the UUIDv1 spec...
    return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)

(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)


In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.

import random
from uuid import uuid1

def uuid1mc_insecure():
    return uuid1(random.getrandbits(48) | 0x010000000000)

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

Create component to specific module with Angular-CLI

if you want to create along with your module try this

  ng generate m module_name --routing &&  ng generate c component_name

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Use Rescue mode with cd and mount the filesystem. Try to check if any binary files or folder are deleted. If deleted you will have to manually install the rpms to get those files back.

https://askubuntu.com/questions/92946/cannot-boot-because-kernel-panic-not-syncing-attempted-to-kill-init

Close Form Button Event

Apply the below code where you want to make code to exit application.

System.Windows.Forms.Application.Exit( )

How to parse XML using vba

This is an example OPML parser working with FeedDemon opml files:

Sub debugPrintOPML()

' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx
' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx
' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions
' References: Microsoft XML

Dim xmldoc As New DOMDocument60
Dim oNodeList As IXMLDOMSelection
Dim oNodeList2 As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n As Long, n2 As Long, x As Long

Dim strXPathQuery As String
Dim attrLength As Byte
Dim FilePath As String

FilePath = "rss.opml"

xmldoc.Load CurrentProject.Path & "\" & FilePath

strXPathQuery = "opml/body/outline"
Set oNodeList = xmldoc.selectNodes(strXPathQuery)

For n = 0 To (oNodeList.length - 1)
    Set curNode = oNodeList.Item(n)
    attrLength = curNode.Attributes.length
    If attrLength > 1 Then ' or 2 or 3
        Call processNode(curNode)
    Else
        Call processNode(curNode)
        strXPathQuery = "opml/body/outline[position() = " & n + 1 & "]/outline"
        Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)
        For n2 = 0 To (oNodeList2.length - 1)
            Set curNode = oNodeList2.Item(n2)
            Call processNode(curNode)
        Next
    End If
        Debug.Print "----------------------"
Next

Set xmldoc = Nothing

End Sub

Sub processNode(curNode As IXMLDOMNode)

Dim sAttrName As String
Dim sAttrValue As String
Dim attrLength As Byte
Dim x As Long

attrLength = curNode.Attributes.length

For x = 0 To (attrLength - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
    sAttrValue = curNode.Attributes.Item(x).nodeValue
    Debug.Print sAttrName & " = " & sAttrValue
Next
    Debug.Print "-----------"

End Sub

This one takes multilevel trees of folders (Awasu, NewzCrawler):

...
Call xmldocOpen4
Call debugPrintOPML4(Null)
...

Dim sText4 As String

Sub debugPrintOPML4(strXPathQuery As Variant)

Dim xmldoc4 As New DOMDocument60
'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?
Dim oNodeList As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n4 As Long

If IsNull(strXPathQuery) Then strXPathQuery = "opml/body/outline"

' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx
xmldoc4.async = False
xmldoc4.loadXML sText4
If (xmldoc4.parseError.errorCode <> 0) Then
   Dim myErr
   Set myErr = xmldoc4.parseError
   MsgBox ("You have error " & myErr.reason)
Else
'   MsgBox xmldoc4.xml
End If

Set oNodeList = xmldoc4.selectNodes(strXPathQuery)

For n4 = 0 To (oNodeList.length - 1)
    Set curNode = oNodeList.Item(n4)
    Call processNode4(strXPathQuery, curNode, n4)
Next

Set xmldoc4 = Nothing

End Sub

Sub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)

Dim sAttrName As String
Dim sAttrValue As String
Dim x As Long

For x = 0 To (curNode.Attributes.length - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
    sAttrValue = curNode.Attributes.Item(x).nodeValue
    'If sAttrName = "text"
    Debug.Print strXPathQuery & " :: " & sAttrName & " = " & sAttrValue
    'End If
Next
    Debug.Print ""

If curNode.childNodes.length > 0 Then
    Call debugPrintOPML4(strXPathQuery & "[position() = " & n4 + 1 & "]/" & curNode.nodeName)
End If

End Sub

Sub xmldocOpen4()

Dim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference
Dim oFS
Dim FilePath As String

FilePath = "rss_awasu.opml"
Set oFS = oFSO.OpenTextFile(CurrentProject.Path & "\" & FilePath)
sText4 = oFS.ReadAll
oFS.Close

End Sub

or better:

Sub xmldocOpen4()

Dim FilePath As String

FilePath = "rss.opml"

' function ConvertUTF8File(sUTF8File):
' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA
' loading and conversion from Utf-8 to UTF
sText8 = ConvertUTF8File(CurrentProject.Path & "\" & FilePath)

End Sub

but I don't understand, why xmldoc4 should be loaded each time.

Specified argument was out of the range of valid values. Parameter name: site

When you start with a Specific Page while debugging your project, and you are using Local IIS, you might have filled a wrong value in the Specific Page textbox.

(via Project Properties > Web > Start Action > Specific Page)

Wrong configuration:

Specific Page: "http://localhost/MyApplication/Start/SpecificPage.aspx"
Project Url: "http://localhost/MyApplication"

Right configuration:

Specific Page: "/Start/SpecificPage.aspx"
Project Url: "http://localhost/MyApplication"

Note: Ignore the quotation marks.

Gson: Is there an easier way to serialize a map

In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

How can I reverse a list in Python?

Using some logic

Using some old school logic to practice for interviews.

Swapping numbers front to back. Using two pointers index[0] and index[last]

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
      holder = n[first]
      n[first] = n[last]
      n[last] = holder
      first += 1
      last -= 1
    return n

input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 1, 2, 3, 4, 5, -1]

How to use NULL or empty string in SQL

Some sargable methods...

SELECT *
FROM #T
WHERE SomeCol = '' OR SomeCol IS NULL;

SELECT *
FROM #T
WHERE SomeCol = '' 
UNION ALL
SELECT *
FROM #T
WHERE  SomeCol IS NULL;

SELECT *
FROM #T
WHERE EXISTS ((SELECT NULL UNION SELECT '') INTERSECT SELECT SomeCol);

And some non-sargable ones...

SELECT *
FROM #T
WHERE IIF(SomeCol <> '',0,1) = 1;

SELECT *
FROM #T
WHERE NULLIF(SomeCol,'') IS NULL;

SELECT *
FROM #T
WHERE ISNULL(SomeCol,'') = '';

Fast and simple String encrypt/decrypt in JAVA

Java - encrypt / decrypt user name and password from a configuration file

Code from above link

DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........

// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");      

Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it 
......

// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);

Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

How to make sure that string is valid JSON using JSON.NET

Alternate option using System.Text.Json

For .Net Core one can also use the System.Text.Json namespace and parse using the JsonDocument. Example is an extension method based on the namespace operations:

public static bool IsJsonValid(this string txt)
{
    try { return JsonDocument.Parse(txt) != null; } catch {}

    return false;
}

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

How to hide columns in HTML table?

Here is the another solution to hide dynamically a column

define class for both th and td of the column to hide

<table>
   <tr>
     <th> Column 1 </th>
     <th class="dynamic-hidden-col"> Column 2 </th>
     <th Column 3 </th>
  </tr>
  <tr>
     <td> Value 1 </td>
     <td class="dynamic-hidden-col"> Value 2 </td>
     <td> Value 3 </td>
  </tr>
     <td> row 2 Value 1 </td>
     <td class="dynamic-hidden-col"> row 2 Value 2 </td>
     <td> row 2 Value 3 </td>
  <tr>
</table>

Here is the Jquery script for hide column.

$('#hide-col').click(function () {      
    $(".dynmic-hidden-col").hide();
});

This way the table column can be hidden dynamically.

Hidden Features of Java

Self-bound generics:

class SelfBounded<T extends SelfBounded<T>> {
}

http://www.artima.com/weblogs/viewpost.jsp?thread=136394

JSON Stringify changes time of date because of UTC

JSON uses the Date.prototype.toISOString function which does not represent local time -- it represents time in unmodified UTC -- if you look at your date output you can see you're at UTC+2 hours, which is why the JSON string changes by two hours, but if this allows the same time to be represented correctly across multiple time zones.

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

For SVG elements

Using something like selection.node().getBBox() you get values like

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

For HTML elements

Use selection.node().getBoundingClientRect()

How to use css style in php

I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.

What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.

How can I parse a local JSON file from assets folder into a ListView?

Using OKIO

public static String readJsonFromAssets(Context context, String filePath) {
    
        try {
            InputStream input = context.getAssets().open(filePath);
            BufferedSource source = Okio.buffer(Okio.source(input));
            return source.readByteString().string(Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
}

and then...

String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json

Type reviewType = new TypeToken<List<Object>>() {}.getType();

if (data != null) {
    Object object = new Gson().fromJson(data, reviewType);
}

Python dictionary: Get list of values for list of keys

A little speed comparison:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

UPDATE: For large random lists and maps I had a bit different results:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

UPDATE for Python 3.6.4:

import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, results for Python 3.6.4 is almost the same.

Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with

Rails.cache.clear

That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).

Update:

You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

How to use regex in String.contains() method in Java

As of Java 11 one can use Pattern#asMatchPredicate which returns Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate offers and, or and negate methods.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

How do I set ANDROID_SDK_HOME environment variable?

from command prompt:

set ANDROID_SDK_HOME=C:\[wherever your sdk folder is]

should do the trick.

What's the difference between .NET Core, .NET Framework, and Xamarin?

.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore. enter image description here

What is the best way to connect and use a sqlite database from C#

I've used this with great success:

http://system.data.sqlite.org/

Free with no restrictions.

(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)

--Bruce

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

Pass command parameter to method in ViewModel in WPF?

Just using Data Binding syntax. For example,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

Split string into array of characters?

the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....

Private Function characterArray(ByVal my_string As String) As String()
  'create a temporary string to store a new string of the same characters with spaces
  Dim tempString As String = ""
  'cycle through the characters and rebuild my_string as a string with spaces 
  'and assign the result to tempString.  
  For Each c In my_string
     tempString &= c & " "
  Next
  'return return tempString as a character array.  
  Return tempString.Split()
End Function

add image to uitableview cell

Swift 5 solution

cell.imageView?.image = UIImage.init(named: "yourImageName")

Get the current script file name

Here is a list what I've found recently searching an answer:

//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';

//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';

// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';

// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';

//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';

// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);

Don't forget to remove :)

<br>

Landscape printing from HTML

I tried Denis's answer and hit some problems (portrait pages didn't print properly after going after landscape pages), so here is my solution:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  background: #CCCCCC;_x000D_
}_x000D_
_x000D_
div.page {_x000D_
  margin: 10px auto;_x000D_
  border: solid 1px black;_x000D_
  display: block;_x000D_
  page-break-after: always;_x000D_
  width: 209mm;_x000D_
  height: 296mm;_x000D_
  overflow: hidden;_x000D_
  background: white;_x000D_
}_x000D_
_x000D_
div.landscape-parent {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.landscape {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.content {_x000D_
  padding: 10mm;_x000D_
}_x000D_
_x000D_
body,_x000D_
div,_x000D_
td {_x000D_
  font-size: 13px;_x000D_
  font-family: Verdana;_x000D_
}_x000D_
_x000D_
@media print {_x000D_
  body {_x000D_
    background: none;_x000D_
  }_x000D_
  div.page {_x000D_
    width: 209mm;_x000D_
    height: 296mm;_x000D_
  }_x000D_
  div.landscape {_x000D_
    transform: rotate(270deg) translate(-296mm, 0);_x000D_
    transform-origin: 0 0;_x000D_
  }_x000D_
  div.portrait,_x000D_
  div.landscape,_x000D_
  div.page {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    border: none;_x000D_
    background: none;_x000D_
  }_x000D_
}
_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    First page in Portrait mode_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page landscape-parent">_x000D_
  <div class="landscape">_x000D_
    <div class="content">_x000D_
      Second page in Landscape mode (correctly shows horizontally in browser and prints rotated in printer)_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    Third page in Portrait mode_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

bash export command

Are you certain that the software (and not yourself, since your test actually only shows the shell used as default for your user) uses /bin/bash ?

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

I also got the same error using the code:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.UseDefaultCredentials = false;
// smtp.EnableSsl = true;
smtp.Send(mail);

But moving 2 lines upward fixed the problem:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.Send(mail);

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

Reading int values from SqlDataReader

This should work:

txtfarmersize = Convert.ToInt32(reader["farmsize"]);

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is only acceptable on TIMESTAMP fields. DATETIME fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.

relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

A non-blocking read on a subprocess.PIPE in Python

Try wexpect, which is the windows alternative of pexpect.

import wexpect

p = wexpect.spawn('myprogram.exe')
p.stdout.readline('.')               // regex pattern of any character
output_str = p.after()

How to close IPython Notebook properly?

In the browser session you can also go to Kernel and then click Restart and Clear Output.

How to round double to nearest whole number and then convert to a float?

For what is worth:

the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer

+-------+--------+
| input | output |
+-------+--------+
|     1 |      0 |
|     2 |      0 |
|     3 |      5 |
|     4 |      5 |
|     5 |      5 |
|     6 |      5 |
|     7 |      5 |
|     8 |     10 |
|     9 |     10 |
+-------+--------+

private int roundClosest(final int i, final int k) {
    int deic = (i % k);
    if (deic <= (k / 2.0)) {
        return (int) (Math.floor(i / (double) k) * k);
    } else {
        return (int) (Math.ceil(i / (double) k) * k);
    }
}

How to pre-populate the sms body text via an html link

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

This works on my iPhone 5S!

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

How to remove close button on the jQuery UI dialog?

Here is another option just using CSS that does not over ride every dialog on the page.

The CSS

.no-close .ui-dialog-titlebar-close {display: none }

The HTML

<div class="selector" title="No close button">
    This is a test without a close button
</div>

The Javascript.

$( ".selector" ).dialog({ dialogClass: 'no-close' });

Working Example

Date only from TextBoxFor()

The Template Editor will work for display purposes only. If you use the same editor (which makes sense because its an editor) and you supplied a value like 31/01/2010 - you'll get an error message saying the format is invalid.

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

Service Temporarily Unavailable Magento?

Simply delete the maintenance.flag file in root folder and then delete the files of cache folder and session folder inside var/ folder.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

PDO mysql: How to know if insert was successful

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }

Draw path between two points using Google Maps Android API v2

First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.

 public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString( sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString( destlat));
        urlString.append(",");
        urlString.append(Double.toString( destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        urlString.append("&key=YOUR_API_KEY");
        return urlString.toString();
 }

This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

This parser will return us string. We will call it like that.

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);

Now we will send this string to our drawpath function. The drawpath function is

public void drawPath(String  result) {

    try {
            //Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);
           Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                    .geodesic(true)
                    );
           /*
           for(int z = 0; z<list.size()-1;z++){
                LatLng src= list.get(z);
                LatLng dest= list.get(z+1);
                Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                .width(2)
                .color(Color.BLUE).geodesic(true));
            }
           */
    } 
    catch (JSONException e) {

    }
} 

Above code will draw the path on mMap. The code of decodePoly is

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng( (((double) lat / 1E5)),
                 (((double) lng / 1E5) ));
        poly.add(p);
    }

    return poly;
}

As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was

private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

I hope it will help.

Preferred way to create a Scala list

And for simple cases:

val list = List(1,2,3) 

:)