Programs & Examples On #Microsoft chart controls

0

Inserting created_at data with Laravel

$data = array();
$data['created_at'] =new \DateTime();
DB::table('practice')->insert($data);

Depend on a branch or tag using a git URL in a package.json?

On latest version of NPM you can just do:

npm install gitAuthor/gitRepo#tag

If the repo is a valid NPM package it will be auto-aliased in package.json as:

{ "NPMPackageName": "gitAuthor/gitRepo#tag" }

If you could add this to @justingordon 's answer there is no need for manual aliasing now !

When to use dynamic vs. static libraries

If the library is static, then at link time the code is linked in with your executable. This makes your executable larger (than if you went the dynamic route).

If the library is dynamic then at link time references to the required methods are built in to your executable. This means that you have to ship your executable and the dynamic library. You also ought to consider whether shared access to the code in the library is safe, preferred load address among other stuff.

If you can live with the static library, go with the static library.

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

Alternative to iFrames with HTML5

You can use object and embed, like so:

<object data="http://www.web-source.net" width="600" height="400">
    <embed src="http://www.web-source.net" width="600" height="400"> </embed>
    Error: Embedded data could not be displayed.
</object>

Which isn't new, but still works. I'm not sure if it has the same functionality though.

Push method in React Hooks (useState)?

You can append array of Data at the end of custom state:

  const [vehicleData, setVehicleData] = React.useState<any[]>([]);
  setVehicleData(old => [...old, ...newArrayData]);

For example, In below, you appear an example of axios:

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        {
          url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
          method: 'get',
        }
      );
      setVehicleData(old => [...old, ...result.data.data]);
    };

    fetchData();
  }, [page]);

Python Binomial Coefficient

Here's a version that actually uses the correct formula . :)

#! /usr/bin/env python

''' Calculate binomial coefficient xCy = x! / (y! (x-y)!)
'''

from math import factorial as fac


def binomial(x, y):
    try:
        return fac(x) // fac(y) // fac(x - y)
    except ValueError:
        return 0


#Print Pascal's triangle to test binomial()
def pascal(m):
    for x in range(m + 1):
        print([binomial(x, y) for y in range(x + 1)])


def main():
    #input = raw_input
    x = int(input("Enter a value for x: "))
    y = int(input("Enter a value for y: "))
    print(binomial(x, y))


if __name__ == '__main__':
    #pascal(8)
    main()

...

Here's an alternate version of binomial() I wrote several years ago that doesn't use math.factorial(), which didn't exist in old versions of Python. However, it returns 1 if r is not in range(0, n+1).

def binomial(n, r):
    ''' Binomial coefficient, nCr, aka the "choose" function 
        n! / (r! * (n - r)!)
    '''
    p = 1    
    for i in range(1, min(r, n - r) + 1):
        p *= n
        p //= i
        n -= 1
    return p

Stopping Docker containers by image name - Ubuntu

For Docker version 18.09.0 I found that format flag won't be needed

docker rm $(docker stop $(docker ps -a -q -f ancestor=<image-name>))

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

Wrap long lines in Python

There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:

msg = (
    'This message is so long, that it requires '
    'more than {x} lines.{sep}'
    'and you may want to add more.').format(
        x=x, sep=2*'\n')
print(msg)

Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered). The advantages are same with what is described below, the difference is that you can do it anywhere. Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg clearly (compare with msg += one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a + on one random line ?).

Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.

A close alternative is:

msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)

Though the first is preferable.

The other approach is like the previous ones, though it starts the message on the line below the print. The reason for this is to gain space on the left, otherwise the print( itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print above them. So if your message was already long, this way it's forced to be spread over even more lines.

Contrast:

raise TypeError('aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa')

with this (suggested here):

raise TypeError(
    'aaaaaaaaaaaaaaaaaaaaaaaa' +
    'aaaaaaaaaaaaaaaaaaaaaaaa')

The line spread was reduced. Of course this last approach does no apply so much to print, because it is a short call. But it does apply to exceptions.

A variation you can have is:

raise TypeError((
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaa {x} aaaaa').format(x=x))

Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.

Stopping fixed position scrolling at a certain point?

my solution

$(window).scroll(function(){
        if($(this).scrollTop()>425) {
            $("#theRelative").css("margin-top",$(this).scrollTop()-425);
            }   else {
                $("#theRelative").css("margin-top",$(this).scrollTop()-0);
                }
            });
            });

Make Axios send cookies in its requests automatically

You can use withCredentials property to pass cookies in the request.

axios.get(`api_url`, { withCredentials: true })

By setting { withCredentials: true } you may encounter cross origin issue. To solve that you need to use

expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));

Here you can read about withCredentials

Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

Check if any service is listening on port 5037, and kill it. You can use lsof for this:

$ lsof -i :5037
$ kill <PID Process>

Then try

$ adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

This solved my problem.

HTTP POST using JSON in Java

It's probably easiest to use HttpURLConnection.

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

You'll use JSONObject or whatever to construct your JSON, but not to handle the network; you need to serialize it and then pass it to an HttpURLConnection to POST.

Check if element is visible in DOM

Here's the code I wrote to find the only visible among a few similar elements, and return the value of its "class" attribute without jQuery:

  // Build a NodeList:
  var nl = document.querySelectorAll('.myCssSelector');

  // convert it to array:
  var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));

  // now find the visible (= with offsetWidth more than 0) item:
  for (i =0; i < myArray.length; i++){
    var curEl = myArray[i];
    if (curEl.offsetWidth !== 0){
      return curEl.getAttribute("class");
    }
  }

Disabling Strict Standards in PHP 5.4

Heads up, you might need to restart LAMP, Apache or whatever your using to make this take affect. Racked our brains for a while on this one, seemed to make no affect until services were restarted, presumably because the website was caching.

How to prevent ENTER keypress to submit a web form?

Please check this article How to prevent ENTER keypress to submit a web form?

_x000D_
_x000D_
$(“.pc_prevent_submit”).ready(function() {_x000D_
  $(window).keydown(function(event) {_x000D_
    if (event.keyCode == 13) {_x000D_
      event.preventDefault();_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form class=”pc_prevent_submit” action=”” method=”post”>_x000D_
  <input type=”text” name=”username”>_x000D_
  <input type=”password” name=”userpassword”>_x000D_
  <input type=”submit” value=”submit”>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I stop a While loop?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period

Tool to monitor HTTP, TCP, etc. Web Service traffic

I second Wireshark. It is very powerful and versatile. And since this tool will work not only on Windows but also on Linux or Mac OSX, investing your time to learn it (quite easy actually) makes sense. Whatever the platform or the language you use, it makes sense.

Regards,

Richard Just Programmer http://sili.co.nz/blog

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

PostgreSQL 'NOT IN' and subquery

When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki

SELECT mac, creation_date 
FROM logs lo
WHERE logs_type_id=11
AND NOT EXISTS (
  SELECT *
  FROM consols nx
  WHERE nx.mac = lo.mac
  );

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

How to open the Chrome Developer Tools in a new window?

If you need to open the DevTools press ctrl-shift-i.

If the DevTools window is already opened you can use the ctrl-shift-d shortcut; it switches the window into a detached mode.

For example in my case the electron application window (Chrome) is really small.

enter image description here

It's not possible to use any other suggestions except the ctrl-shift-d shortcut

Add an image in a WPF button

You can set the button's background to the image if you then want to overlay text.

<Button>
   <Button.Background>
     <ImageBrush ImageSource="/AssemblyName;component/Pictures/img.jpg"/>
   </Button.Background>
   <TextBlock>Blablabla</TextBlock>
</Button>

Watch out for the image source syntax. See this question for help.

Can Windows' built-in ZIP compression be scripted?

There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.

This is not the perfect solution (or the one you asked for) but a decent work-a-round.

Drop shadow for PNG image in CSS

There's a proposed feature which you could use for arbitrarily shaped drop shadows. You could see it here, courtesy of Lea Verou:

http://www.netmagazine.com/features/hot-web-standards-css-blending-modes-and-filters-shadow-dom

Browser support is minimal, though.

Python/Json:Expecting property name enclosed in double quotes

I've checked your JSON data

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

in http://jsonlint.com/ and the results were:

Error: Parse error on line 1:
{   'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'

modifying it to the following string solve the JSON error:

{
    "http://example.org/about": {
        "http://purl.org/dc/terms/title": [{
            "type": "literal",
            "value": "Anna's Homepage"
        }]
    }
}

How to get the containing form of an input?

I needed to use element.attr('form') instead of element.form.

I use Firefox on Fedora 12.

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

Android: How to set password property in an edit text?

You need to use PasswordTransformationMethod.getInstance() instead of new PasswordTransformationMethod().

Can regular expressions be used to match nested patterns?

Probably working Perl solution, if the string is on one line:

my $NesteD ;
$NesteD = qr/ \{( [^{}] | (??{ $NesteD }) )* \} /x ;

if ( $Stringy =~ m/\b( \w+$NesteD )/x ) {
    print "Found: $1\n" ;
  }

HTH

EDIT: check:

And one more thing by Torsten Marek (who had pointed out correctly, that it's not a regex anymore):

Visual Studio : short cut Key : Duplicate Line

Ctrl + C + V works for me on VS2012 with no extension.

Take screenshots in the iOS simulator

It's just as simple as command+s or File > Save Screen Shot in iOS Simulator. It will appear on your desktop by default.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

For me the problem was that I haven't created any virtual devices after fresh installation of android studio. So, expo kept complaining vaguely about the sdk location while the main issue was the missing virtual devices. Hope this helps somebody in the future, had me searching for a couple of hours.

PS: here you can find out how to create one https://developer.android.com/studio/run/managing-avds

UML diagram shapes missing on Visio 2013

If you don't see stencils creating new document with a template you may open the template directly. In my case they are located at 'C:\Program Files\Microsoft Office\Office15\Visio Content\1049\' Last foler name varies regarding locale, I guess. UML template is named 'DBUML_M.VSTX'

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

Screen width in React Native

In React-Native we have an Option called Dimensions

Include Dimensions at the top var where you have include the Image,and Text and other components.

Then in your Stylesheets you can use as below,

ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}

In this way you can get the device window and height.

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. Consider this:

abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of 10.1.1.2 is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Using regular expressions to do mass replace in Notepad++ and Vim

In vim

:%s/<option value='.\{1,}' >//

or

:%s/<option value='.\+' >//

In vim regular expressions you have to escape the one-or-more symbol, capturing parentheses, the bounded number curly braces and some others.

See :help /magic to see which special characters need to be escaped (and how to change that).

MySQL JOIN with LIMIT 1 on joined table

I like more another approach described in a similar question: https://stackoverflow.com/a/11885521/2215679

This approach is better especially in case if you need to show more than one field in SELECT. To avoid Error Code: 1241. Operand should contain 1 column(s) or double sub-select for each column.

For your situation the Query should looks like:

SELECT
 c.id,
 c.title,
 p.id AS product_id,
 p.title AS product_title
FROM categories AS c
JOIN products AS p ON
 p.id = (                                 --- the PRIMARY KEY
  SELECT p1.id FROM products AS p1
  WHERE c.id=p1.category_id
  ORDER BY p1.id LIMIT 1
 )

Get the POST request body from HttpServletRequest

If the request body is empty, then it simply means that it's already been consumed beforehand. For example, by a request.getParameter(), getParameterValues() or getParameterMap() call. Just remove the lines doing those calls from your code.

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

react native get TextInput value

_x000D_
_x000D_
export default class App extends Component {_x000D_
  state = { username: '', password: '' }_x000D_
_x000D_
  onChangeText = (key, val) => {_x000D_
    this.setState({ [key]: val})_x000D_
  }_x000D_
  _x000D_
  render() { _x000D_
    return (_x000D_
      <View style={styles.container}>_x000D_
          <Text>Login Form</Text>_x000D_
          <TextInput_x000D_
            placeholder='Username'_x000D_
            onChangeText={val => this.onChangeText('username', val)}_x000D_
            style={styles.input}_x000D_
          />_x000D_
          <TextInput_x000D_
            placeholder='Password'_x000D_
            onChangeText={val => this.onChangeText('password', val)}_x000D_
            style={styles.input}_x000D_
            secureTextEntry={true}_x000D_
          />      _x000D_
      </View>_x000D_
    );_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Hope this will solve your problem

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

FYI Under certain network conditions your hostname may change or be incorrect. If you are on a mac the following will let you set your hostname fairly permanently:

sudo scutil --set HostName correct-name

Apache and Node.js on the Same Server


Instructions to run node server along apache2(v2.4.xx) server:

In order to pipe all requests on a particular URL to your Node.JS application create CUSTOM.conf file inside /etc/apache2/conf-available directory, and add following line to the created file:

ProxyPass /node http://localhost:8000/

Change 8000 to the prefered port number for node server.
Enable custom configurations with following command:

$> sudo a2enconf CUSTOM

CUSTOM is your newly created filename without extension, then enable proxy_http with the command:

$> sudo a2enmod proxy_http

it should enable both proxy and proxy_http modules. You can check whether module is enabled or not with:

$> sudo a2query -m MODULE_NAME

After configuration and modules enabled, you will need to restart apache server:

$> sudo service apache2 restart

Now you can execute node server. All requests to the URL/node will be handled by node server.

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

Darken background image on hover

If you have to use the current image and get a darker image then you need to create a new one. Else you can simply reduce the opacity of the .image class and the in the .image:hover you can put a higher value for opacity. But then the image without hover would look pale.

The best way would be to create two images and add the following :

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.9;   
}
.image:hover{
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook_hover.png');
}
}

Is object empty?

var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(a) {
    return Object.prototype.toString.call(a) === '[object Array]'
}
function isObject(a) {
    return Object.prototype.toString.call(a) === '[object Object]'
}
function isEmpty(a) {
    if (null == a || "" == a)return!0;
    if ("number" == typeof a || "string" == typeof a)return!1;
    var b = !0;
    if (isArray(a)) {
        if (!a.length)return!0;
        for (var c = 0; c < a.length; c++)isEmpty(a[c]) || (b = !1);
        return b
    }
    if (isObject(a)) {
        for (var d in a)hasOwnProperty.call(a, d) && (isEmpty(a[d]) || (b = !1));
        return b
    }
    return!0
}

How to increase font size in a plot in R?

Thus, to summarise the existing discussion, adding

cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5

to your plot, where 1.5 could be 2, 3, etc. and a value of 1 is the default will increase the font size.

x <- rnorm(100)

cex doesn't change things

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE)

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE, 
     cex=1.5)

enter image description here

Add cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5

hist(x, xlim=range(x),
     xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE, 
     cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)

enter image description here

Can I run CUDA on Intel's integrated graphics processor?

Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.

Link: http://www.pgroup.com/products/pgiworkstation.htm

'do...while' vs. 'while'

The most common scenario I run into where I use a do/while loop is in a little console program that runs based on some input and will repeat as many times as the user likes. Obviously it makes no sense for a console program to run no times; but beyond the first time it's up to the user -- hence do/while instead of just while.

This allows the user to try out a bunch of different inputs if desired.

do
{
   int input = GetInt("Enter any integer");
   // Do something with input.
}
while (GetBool("Go again?"));

I suspect that software developers use do/while less and less these days, now that practically every program under the sun has a GUI of some sort. It makes more sense with console apps, as there is a need to continually refresh the output to provide instructions or prompt the user with new information. With a GUI, in contrast, the text providing that information to the user can just sit on a form and never need to be repeated programmatically.

What is the equivalent of "none" in django templates?

{% if profile.user.first_name %} works (assuming you also don't want to accept '').

if in Python in general treats None, False, '', [], {}, ... all as false.

How to get Python requests to trust a self signed SSL certificate?

Setting export SSL_CERT_FILE=/path/file.crt should do the job.

How to return a boolean method in java?

try this:

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            return true;
        }

}

if (verifyPwd()==true){
    addNewUser();
}
else {
    // passwords do not match
}

How to zero pad a sequence of integers in bash so that all have the same width?

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.

Running vbscript from batch file

Just try this code:

start "" "C:\Users\DiPesh\Desktop\vbscript\welcome.vbs"

and save as .bat, it works for me

Resolving a Git conflict with binary files

git checkout accepts an --ours or --theirs option for cases like this. So if you have a merge conflict, and you know you just want the file from the branch you are merging in, you can do:

$ git checkout --theirs -- path/to/conflicted-file.txt

to use that version of the file. Likewise, if you know you want your version (not the one being merged in) you can use

$ git checkout --ours -- path/to/conflicted-file.txt

jQuery click event not working after adding class

Based on @Arun P Johny this is how you do it for an input:

<input type="button" class="btEdit" id="myButton1">

This is how I got it in jQuery:

$(document).on('click', "input.btEdit", function () {
    var id = this.id;
    console.log(id);
});

This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

UPDATE

Though it would be better to say:

$(document).on('click', "input.btEdit", function () {
    var id = $(this).id;
    console.log(id);
});

Since this is JQuery's syntax, even though both will work.

How to get coordinates of an svg element?

svg.selectAll("rect")
.attr('x',function(d,i){
    // get x coord
    console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
    // get y coord
    console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
    // get dx coord
    console.log(parseInt(d3.select(this).attr('dx')))
})

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

Using port number in Windows host file

You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.

Example

git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop

Explanation

Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Java: Retrieving an element from a HashSet

One of the easiest ways is to convert to Array:

for(int i = 0; i < set.size(); i++) {
    System.out.println(set.toArray()[i]);
}

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

How to debug "ImagePullBackOff"?

I forgot to push the image tagged 1.0.8 to the ECR (AWS images hub)... If you are using Helm and upgrade by:

helm upgrade minta-user ./src/services/user/helm-chart

make sure that image tag inside values.yaml is pushed (to ECR or Docker Hub, etc) for example: (this is my helm-chart/values.yaml)

replicaCount: 1

image:
   repository:dkr.ecr.us-east-1.amazonaws.com/minta-user
   tag: 1.0.8

you need to make sure that the image:1.0.8 is pushed!

How to upload files on server folder using jsp

You can only use absolute path http://grand-shopping.com/<"some folder"> is not an absolute path.

Either you can use a path inside the application which is vurneable or you can use server specific path like in

windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/

Change width of select tag in Twitter Bootstrap

For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:

@media (min-width: $screen-xs) {

    .selectwidthauto {
         width:auto !important;
         display: inline-block;
    }

}

Namespace for [DataContract]

DataContractAttribute Class is in the System.Runtime.Serialization namespace.

You should add a reference to System.Runtime.Serialization.dll. That assembly isn't referenced by default though. To add the reference to your project you have to go to References -> Add Reference in the Solution Explorer and add an assembly reference manually.

What's the Kotlin equivalent of Java's String[]?

For Strings and other types, you just use Array<*>. The reason IntArray and others exist is to prevent autoboxing.

So int[] relates to IntArray where Integer[] relates to Array<Int>.

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

Installing Google Protocol Buffers on mac

HomeBrew versions has been removed and formulaes have been emptied. Therefore, my advice is to install it manually following the following steps.

For the time being you will need to build and install the Protocol Buffers toolset manually.

  1. Download source code: https://github.com/google/protobuf/releases/download/v2.4.1/protobuf-2.4.1.tar.gz

  2. tar xvfz protobuf-2.4.1.tar.gz

  3. cd protobuf-2.4.1

  4. Run ./configure

  5. Edit src/google/protobuf/message.cc, add #include at the top of the file

  6. Run make command from root of the folder, i.e. protobuf-2.4.1/

  7. Run sudo make install

  8. Run /usr/local/bin/protoc --version to check the version of protobuf compiler version The terminal output should be:

    Version: libprotoc 2.4.1

Detect Windows version in .net

Detect OS Version:

    public static string OS_Name()
    {
        return (string)(from x in new ManagementObjectSearcher(
            "SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>() 
            select x.GetPropertyValue("Caption")).FirstOrDefault();
    }

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.

  • open Excel
  • press "Alt+F11"
  • Double-click on the worksheet that you want to apply the change to (listed on the left)
  • copy/paste the code below
  • adjust the Range(:) input to correspond to the column you will update
  • adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
  • hit save
  • repeat steps above if there are other worksheets in your workbook that need the same code
  • you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry

Copy/Paste Code below:


Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date

End Sub


Good luck...

Can't execute jar- file: "no main manifest attribute"

The above answers were only partly helpful for me. java -cp was part of the answer, but I needed more specific info on how to identify the class to run. Here is what worked for me:

Step 1: find the class I need to run

jar tf /path/to/myjar.jar | more

The top lines of the result were:

META-INF/
META-INF/MANIFEST.MF
somepath/
somepath/App.class
META-INF/maven/
...

App.class contained the main class to run. I'm not 100% sure if you can always assume the class you need is the first one, but it was for me. If it isn't, I'd imagine it isn't too hard to use grep to exclude library-related results to pare the class list down to a manageable size.

From there it was easy: I just use that path (minus the ".class" suffix):

java -cp /path/to/myjar.jar somepath/App

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

Twitter bootstrap progress bar animation on page load

While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.

here's my solution:

JSfiddle: http://jsfiddle.net/vacNJ/

HTML (example):

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>

?

JavaScript:

setTimeout(function(){

    $('.progress .bar').each(function() {
        var me = $(this);
        var perc = me.attr("data-percentage");

        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.css('width', (current_perc)+'%');
            }

            me.text((current_perc)+'%');

        }, 50);

    });

},300);

@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)

EDIT:

A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars. Here's a demo: http://minddust.github.com/bootstrap-progressbar/

Here's the Github repo: https://github.com/minddust/bootstrap-progressbar

JavaScript/jQuery to download file via POST with JSON data

I have been awake for two days now trying to figure out how to download a file using jquery with ajax call. All the support i got could not help my situation until i try this.

Client Side

_x000D_
_x000D_
function exportStaffCSV(t) {_x000D_
   _x000D_
    var postData = { checkOne: t };_x000D_
    $.ajax({_x000D_
        type: "POST",_x000D_
        url: "/Admin/Staff/exportStaffAsCSV",_x000D_
        data: postData,_x000D_
        success: function (data) {_x000D_
            SuccessMessage("file download will start in few second..");_x000D_
            var url = '/Admin/Staff/DownloadCSV?data=' + data;_x000D_
            window.location = url;_x000D_
        },_x000D_
       _x000D_
        traditional: true,_x000D_
        error: function (xhr, status, p3, p4) {_x000D_
            var err = "Error " + " " + status + " " + p3 + " " + p4;_x000D_
            if (xhr.responseText && xhr.responseText[0] == "{")_x000D_
                err = JSON.parse(xhr.responseText).Message;_x000D_
            ErrorMessage(err);_x000D_
        }_x000D_
    });_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Server Side

 [HttpPost]
    public string exportStaffAsCSV(IEnumerable<string> checkOne)
    {
        StringWriter sw = new StringWriter();
        try
        {
            var data = _db.staffInfoes.Where(t => checkOne.Contains(t.staffID)).ToList();
            sw.WriteLine("\"First Name\",\"Last Name\",\"Other Name\",\"Phone Number\",\"Email Address\",\"Contact Address\",\"Date of Joining\"");
            foreach (var item in data)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\"",
                    item.firstName,
                    item.lastName,
                    item.otherName,
                    item.phone,
                    item.email,
                    item.contact_Address,
                    item.doj
                    ));
            }
        }
        catch (Exception e)
        {

        }
        return sw.ToString();

    }

    //On ajax success request, it will be redirected to this method as a Get verb request with the returned date(string)
    public FileContentResult DownloadCSV(string data)
    {
        return File(new System.Text.UTF8Encoding().GetBytes(data), System.Net.Mime.MediaTypeNames.Application.Octet, filename);
        //this method will now return the file for download or open.
    }

Good luck.

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

For people still getting the issue.

I face same problem and seems some .jar file missing.

so try tar -xf apache-jmeter-5.2.1.tgz in the console rather than just right click unzip. And also, try binary package if source package still has an issue. this solve my issue (I am using ubuntu)

What's the difference between SHA and AES encryption?

SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.

You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.

AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.

UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.

Creating an instance of class

Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.

In Line 7, you create an object inside the argument call. So its an error.

And Lines 5 and 6 are invitation for memory leak.

How does one parse XML files?

In Addition you can use XPath selector in the following way (easy way to select specific nodes):

XmlDocument doc = new XmlDocument();
doc.Load("test.xml");

var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'

// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
  book.InnerText="The story began as it was...";
}

Console.WriteLine("Display XML:");
doc.Save(Console.Out);

the documentation

Full width image with fixed height

This can done several ways. I usually do it from my class.

From class

.image
{
    width:100%;


}

and for this your html would be:

<img class="image" src="images/image_name">

or if you want to style it using inline styling then you would just have:

<img style="width:100%; height:60px" id="image" src="images/image_name">

I however recommend doing it from your external style-sheet because as your project grows you will realize that the entire thing is easier managed with separate files for your html and your css.

Java - creating a new thread

run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

SQL - Query to get server's IP address

I know this is an old post, but perhaps this solution can be usefull when you want to retrieve the IP address and TCP port from a Shared Memory connection (e.g. from a script run in SSMS locally on the server). The key is to open a secondary connection to your SQL Server using OPENROWSET, in which you specify 'tcp:' in your connection string. The rest of the code is merely building dynamic SQL to get around OPENROWSET’s limitation of not being able to take variables as its parameters.

DECLARE @ip_address       varchar(15)
DECLARE @tcp_port         int 
DECLARE @connectionstring nvarchar(max) 
DECLARE @parm_definition  nvarchar(max)
DECLARE @command          nvarchar(max)

SET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'
SET @parm_definition  = N'@ip_address_OUT varchar(15) OUTPUT
                        , @tcp_port_OUT   int         OUTPUT';

SET @command          = N'SELECT  @ip_address_OUT = a.local_net_address,
                                  @tcp_port_OUT   = a.local_tcp_port
                          FROM OPENROWSET(''SQLNCLI''
                                 , ''' + @connectionstring + '''
                                 , ''SELECT local_net_address
                                          , local_tcp_port
                                     FROM sys.dm_exec_connections
                                     WHERE session_id = @@spid
                                   '') as a'

EXEC SP_executeSQL @command
                 , @parm_definition
                 , @ip_address_OUT = @ip_address OUTPUT
                 , @tcp_port_OUT   = @tcp_port OUTPUT;


SELECT @ip_address, @tcp_port

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

What does the Excel range.Rows property really do?

I'm not sure, but I think the second parameter is a red herring.

Both .Rows and .Columns take two optional parameters: RowIndex and ColumnIndex. Try to use ColumnIndex, e.g. Rows(ColumnIndex:=2), generates an error for both .Rows and .Columns.

My feeling it's inherited in some sense from the Cells(RowIndex,ColumnIndex) Property but only the first parameter is appropriate.

CodeIgniter Active Record - Get number of returned rows

AND, if you just want to get a count of all the rows in a table

$table_row_count = $this->db->count_all('table_name');

How many characters in varchar(max)

From http://msdn.microsoft.com/en-us/library/ms176089.aspx

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Get dates from a week number in T-SQL

SELECT DATECOL - DATEPART(weekday, DATECOL), DATECOL - DATEPART(weekday, DATECOL) + 7

Get underlined text with Markdown

The simple <u>some text</u> should work for you.

When to throw an exception?

the rule of thumb for throwing exceptions is pretty simple. you do so when your code has entered into an UNRECOVERABLE INVALID state. if data is compromised or you cannot wind back the processing that occurred up to the point then you must terminate it. indeed what else can you do? your processing logic will eventually fail elsewhere. if you can recover somehow then do that and do not throw exception.

in your particular case if you were forced to do something silly like accept money withdrawal and only then check user/pasword you should terminate the process by throwing an exception to notify that something bad has happened and prevent further damage.

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How do I make Git ignore file mode (chmod) changes?

Simple solution:

Hit this Simple command in project Folder(it won't remove your original changes) ...it will only remove changes that had been done while you changed project folder permission

command is below:

git config core.fileMode false

Why this all unnecessary file get modified: because you have changed the project folder permissions with commend sudo chmod -R 777 ./yourProjectFolder

when will you check changes what not you did? you found like below while using git diff filename

old mode 100644
new mode 100755

How to find MySQL process list and to kill those processes?

select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;

Then copy and paste the result back into the terminal. Something like:

KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;

How to close the command line window after running a batch file?

Used this to start Xming, placed the bat file in the Start->Startup directory and now I have xming running on start up.

start "" "C:\Program Files (x86)\Xming\Xming.exe" -screen 0 -clipboard -multiwindow

Set cURL to use local virtual hosts

Actually, curl has an option explicitly for this: --resolve

Instead of curl -H 'Host: yada.com' http://127.0.0.1/something

use curl --resolve 'yada.com:80:127.0.0.1' http://yada.com/something

What's the difference, you ask?

Among others, this works with HTTPS. Assuming your local server has a certificate for yada.com, the first example above will fail because the yada.com certificate doesn't match the 127.0.0.1 hostname in the URL.

The second example works correctly with HTTPS.

In essence, passing a "Host" header via -H does hack your Host into the header set, but bypasses all of curl's host-specific intelligence. Using --resolve leverages all of the normal logic that applies, but simply pretends the DNS lookup returned the data in your command-line option. It works just like /etc/hosts should.

Note --resolve takes a port number, so for HTTPS you would use

curl --resolve 'yada.com:443:127.0.0.1' https://yada.com/something

Runnable with a parameter?

You have two options:

  1. Define a named class. Pass your parameter to the constructor of the named class.

  2. Have your anonymous class close over your "parameter". Be sure to mark it as final.

add a string prefix to each value in a string column using Pandas

df['col'] = 'str' + df['col'].astype(str)

Example:

>>> df = pd.DataFrame({'col':['a',0]})
>>> df
  col
0   a
1   0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
    col
0  stra
1  str0

How to Initialize char array from a string

I'm not sure what your problem is, but the following seems to work OK:

#include <stdio.h>

int main()
{
    const char s0[] = "ABCD";
    const char s1[] = { s0[3], s0[2], s0[1], s0[0], 0 };

    puts(s0);
    puts(s1);
    return 0;
}


Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
cl /Od /D "WIN32" /D "_CONSOLE" /Gm /EHsc /RTC1 /MLd /W3 /c /ZI /TC
   .\Tmp.c
Tmp.c
Linking...

Build Time 0:02


C:\Tmp>tmp.exe
ABCD
DCBA

C:\Tmp>

Edit 9 June 2009

If you need global access, you might need something ugly like this:

#include <stdio.h>

const char *GetString(int bMunged)
{
    static char s0[5] = "ABCD";
    static char s1[5];

    if (bMunged) {
        if (!s1[0])  {
            s1[0] = s0[3]; 
            s1[1] = s0[2];
            s1[2] = s0[1];
            s1[3] = s0[0];
            s1[4] = 0;
        }
        return s1;
    } else {
        return s0;
    }
}

#define S0 GetString(0)
#define S1 GetString(1)

int main()
{
    puts(S0);
    puts(S1);
    return 0;
}

What does 'corrupted double-linked list' mean

For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:

This was due to a function not returning a value it was supposed to.

std::vector<Object> generateStuff(std::vector<Object>& target> {
  std::vector<Object> returnValue;
  editStuff(target);
  // RETURN MISSING
}

Don't know why this was able to compile after all. Probably there was a warning about it.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Alternatively if you don't need to decode the file, such as uploading the file to a website, open(filename, 'rb')

where r = reading, b = binary

Passing argument to alias in bash

to use parameters in aliases, i use this method:

alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'

its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:

alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'

so..

you could, if you need to have that variable in there

alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'

of course...

alias mongodb='./path/to/mongodb/'

would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).

I hope that helps you out :)

What is MVC and what are the advantages of it?

If you follow the stackoverflow podcasts you can hear Jeff (and Geoff?) discuss its greatness. https://blog.stackoverflow.com/2008/08/podcast-17/. But remember that using these separate layers means things are easier in the future--and harder now. And layers can make things slower. And you may not need them. But don't let that stop you from learning what it is--when building big, robust, long-lived systems, it's invaluable.

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

Changing Fonts Size in Matlab Plots

Jonas's answer does not change the font size of the axes. Sergeyf's answer does not work when there are multiple subplots.

Here is a modification of their answers that works for me when I have multiple subplots:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

Trim specific character from a string

expanding on @leaf 's answer, here's one that can take multiple characters:

var trim = function (s, t) {
  var tr, sr
  tr = t.split('').map(e => `\\\\${e}`).join('')
  sr = s.replace(new RegExp(`^[${tr}]+|[${tr}]+$`, 'g'), '')
  return sr
}

Passing parameters to JavaScript files

Another idea I came across was assigning an id to the <script> element and passing the arguments as data-* attributes. The resulting <script> tag would look something like this:

<script id="helper" data-name="helper" src="helper.js"></script>

The script could then use the id to programmatically locate itself and parse the arguments. Given the previous <script> tag, the name could be retrieved like this:

var name = document.getElementById("helper").getAttribute("data-name");

We get name = helper

Does JavaScript have a built in stringbuilder class?

In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);

Creating and writing lines to a file

Set objFSO=CreateObject("Scripting.FileSystemObject")

' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close

'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine= objFile.ReadLine
    Wscript.Echo strLine
Loop
objFile.Close

'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)

Length of a JavaScript object

I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:

var element_count = 0;
for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }

@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

@angular/material/index.d.ts' is not a module

And also ng update @angular/material will update your code and fix all imports

Keep the order of the JSON keys during JSON conversion to CSV

A more verbose, but broadly applicable solution to this sort of problem is to use a pair of data structures: a list to contain the ordering, and a map to contain the relations.

For Example:

{
    "items":
    [
        {
            "WR":"qwe",
            "QU":"asd",
            "QA":"end",
            "WO":"hasd",
            "NO":"qwer"
        },
    ],
    "itemOrder":
        ["WR", "QU", "QA", "WO", "NO"]
}

You iterate the itemOrder list, and use those to look up the map values. Ordering is preserved, with no kludges.

I have used this method many times.

Add context path to Spring Boot application

<!-- Server port-->

server.port=8080

<!--Context Path of the Application-->

server.servlet.context-path=/ems

Command to delete all pods in all kubernetes namespaces

There is no command to do exactly what you asked.

Here are some close matches.

You can delete all the pods in a single namespace with this command:

kubectl delete --all pods --namespace=foo

You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace

kubectl delete --all deployments --namespace=foo

You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command:

kubectl delete --all namespaces

However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable.

This command will delete all the namespaces except kube-system, which might be useful:

for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
  kubectl delete ns $each
done

What is the best way to call a script from another script?

Another way:

File test1.py:

print "test1.py"

File service.py:

import subprocess

subprocess.call("test1.py", shell=True)

The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.

Documentation: Python 2, Python 3

Left Outer Join using + sign in Oracle 11g

I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

Changing width property of a :before css selector using JQuery

You may try to inherit property from the base class:

_x000D_
_x000D_
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
    var element = document.getElementById('box');_x000D_
    width += 0.0625;_x000D_
    element.style.width = width + 'em';_x000D_
    if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
    /* Set property */_x000D_
    width:4em;_x000D_
    height:2em;_x000D_
    background-color:#d42;_x000D_
    position:relative;_x000D_
}_x000D_
.box:after {_x000D_
    /* Inherit property */_x000D_
    width:inherit;_x000D_
    content:"";_x000D_
    height:1em;_x000D_
    background-color:#2b4;_x000D_
    position:absolute;_x000D_
    top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
_x000D_
_x000D_

How to drop column with constraint?

Find the default constraint with this query here:

SELECT
    df.name 'Constraint Name' ,
    t.name 'Table Name',
    c.NAME 'Column Name'
FROM sys.default_constraints df
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id

This gives you the name of the default constraint, as well as the table and column name.

When you have that information you need to first drop the default constraint:

ALTER TABLE dbo.YourTable
DROP CONSTRAINT name-of-the-default-constraint-here

and then you can drop the column

ALTER TABLE dbo.YourTable DROP COLUMN YourColumn

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

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 ")).

How can I convert a VBScript to an executable (EXE) file?

You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for $60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.

Android refresh current activity

You can Try this:

        CookieSyncManager.createInstance(this);         
        CookieManager cookieManager = CookieManager.getInstance();        
        cookieManager.removeAllCookie();        
        Intent intent= new Intent(YourCurrent.this, YourCurrent.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

The import org.junit cannot be resolved

In case you want to create your own Test Class. In Eclipse go to File -> New -> J Unit Test Case. You can then choose all your paths and testing class setup within the wizard pop-up.

Homebrew: Could not symlink, /usr/local/bin is not writable

I found same problem, we can resolve in three steps:-

Step 1

sudo chown -R $(whoami) $(brew --prefix)/*

Step 2

brew doctor

Step 3

brew prune

If you still get any linking problem, lets say for mysql, just write

brew link mysql

This will work.

Shell script current directory?

Most answers get you the current path and are context sensitive. In order to run your script from any directory, use the below snippet.

DIR="$( cd "$( dirname "$0" )" && pwd )"

By switching directories in a subshell, we can then call pwd and get the correct path of the script regardless of context.

You can then use $DIR as "$DIR/path/to/file"

Allow access permission to write in Program Files of Windows 7

You can add an access to IIS User for folders of Website or Web Application that you want write or rewrite in it.

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

How to have EditText with border in Android Lollipop

You can use a drawable. Create a drawable layout file in your drawable folder. Paste this code. You can as well modify it - border.xml.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
    android:width="1dp"
    android:color="@color/divider" />
<solid
    android:color="#00FFFFFF"
    android:paddingLeft="10dp"
    android:paddingTop="10dp"/>
<padding
    android:left="10dp"
    android:top="10dp"
    android:right="10dp"
    android:bottom="10dp" />
</shape>

in your EditText view, add

android:background="@drawable/border"

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Initializing a static std::map<int, int> in C++

Best way is to use a function:

#include <map>

using namespace std;

map<int,int> create_map()
{
  map<int,int> m;
  m[1] = 2;
  m[3] = 4;
  m[5] = 6;
  return m;
}

map<int,int> m = create_map();

Start an Activity with a parameter

Just add extra data to the Intent you use to call your activity.

In the caller activity :

Intent i = new Intent(this, TheNextActivity.class);
i.putExtra("id", id);
startActivity(i);

Inside the onCreate() of the activity you call :

Bundle b = getIntent().getExtras();
int id = b.getInt("id");

Creating a .dll file in C#.Net

You need to make a class library and not a Console Application. The console application is translated into an .exe whereas the class library will then be compiled into a dll which you can reference in your windows project.

  • Right click on your Console Application -> Properties -> Change the Output type to Class Library

enter image description here

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Batch Files - Error Handling

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

Accessing the index in 'for' loops?

If there is no duplicate value in the list:

for i in ints:
    indx = ints.index(i)
    print(i, indx)

How to disable registration new users in Laravel

In Laravel 5.5

I was trying to accomplish the same problem in Laravel 5.5. Instead of using Auth::routes() in the web.php routes file, I only included the login/logout routes:

Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

Django model "doesn't declare an explicit app_label"

In my case, I was trying the same import in manage.py shell. The shell was messed up with the updated db. I mean, I forgot to restart my shell after updating the DB.

To resolve the issue, I had to stop the shell by the following command:

>>> exit()

then restart the shell by the following command:

$ python3 manage.py shell

Hope this will help somebody like me.

How to create and download a csv file from php script?

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line);
}

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

And you can use it like this:

array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);

Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   

Check if space is in a string

word = ' '
while True:
    if ' ' in word:
        word = raw_input("Please enter a single word: ")
    else:
        print "Thanks"
        break

This is more idiomatic python - comparison against True or False is not necessary - just use the value returned by the expression ' ' in word.

Also, you don't need to use pastebin for such a small snippet of code - just copy the code into your post and use the little 1s and 0s button to make your code look like code.

How to handle configuration in Go

I wrote a simple ini config library in golang.

https://github.com/c4pt0r/cfg

goroutine-safe, easy to use

package cfg
import (
    "testing"
)

func TestCfg(t *testing.T) {
    c := NewCfg("test.ini")
    if err := c.Load() ; err != nil {
        t.Error(err)
    }
    c.WriteInt("hello", 42)
    c.WriteString("hello1", "World")

    v, err := c.ReadInt("hello", 0)
    if err != nil || v != 42 {
        t.Error(err)
    }

    v1, err := c.ReadString("hello1", "")
    if err != nil || v1 != "World" {
        t.Error(err)
    }

    if err := c.Save(); err != nil {
        t.Error(err)
    }
}

===================Update=======================

Recently I need an INI parser with section support, and I write a simple package:

github.com/c4pt0r/cfg

u can parse INI like using "flag" package:

package main

import (
    "log"
    "github.com/c4pt0r/ini"
)

var conf = ini.NewConf("test.ini")

var (
    v1 = conf.String("section1", "field1", "v1")
    v2 = conf.Int("section1", "field2", 0)
)

func main() {
    conf.Parse()

    log.Println(*v1, *v2)
}

Hibernate: hbm2ddl.auto=update in production?

It's not safe, not recommended, but it's possible.

I have experience in an application using the auto-update option in production.

Well, the main problems and risks found in this solution are:

  • Deploy in the wrong database. If you commit the mistake to run the application server with a old version of the application (EAR/WAR/etc) in the wrong database... You will have a lot of new columns, tables, foreign keys and errors. The same problem can occur with a simple mistake in the datasource file, (copy/paste file and forgot to change the database). In resume, the situation can be a disaster in your database.
  • Application server takes too long to start. This occur because the Hibernate try to find all created tables/columns/etc every time you start the application. He needs to know what (table, column, etc) needs to be created. This problem will only gets worse as the database tables grows up.
  • Database tools it's almost impossible to use. To create database DDL or DML scripts to run with a new version, you need to think about what will be created by the auto-update after you start the application server. Per example, If you need to fill a new column with some data, you need to start the application server, wait to Hibernate crete the new column and run the SQL script only after that. As can you see, database migration tools (like Flyway, Liquibase, etc) it's almost impossible to use with auto-update enabled.
  • Database changes is not centralized. With the possibility of the Hibernate create tables and everything else, it's hard to watch the changes on database in each version of the application, because most of them are made automatically.
  • Encourages garbage on database. Because of the "easy" use of auto-update, there is a chance your team neglecting to drop old columns and old tables, because the hibernate auto-update can't do that.
  • Imminent disaster. The imminent risk of some disaster to occur in production (like some people mentioned in other answers). Even with an application running and being updated for years, I don't think it's a safe choice. I never felt safe with this option being used.

So, I will not recommend to use auto-update in production.

If you really want to use auto-update in production, I recommend:

  • Separated networks. Your test environment cannot access the homolog environment. This helps prevent a deployment that was supposed to be in the Test environment change the Homologation database.
  • Manage scripts order. You need to organize your scripts to run before your deploy (structure table change, drop table/columns) and script after the deploy (fill information for the new columns/tables).

And, different of the another posts, I don't think the auto-update enabled it's related with "very well paid" DBAs (as mentioned in other posts). DBAs have more important things to do than write SQL statements to create/change/delete tables and columns. These simple everyday tasks can be done and automated by developers and only passed for DBA team to review, not needing Hibernate and DBAs "very well paid" to write them.

How to access to a child method from the parent in vue.js

You can use ref.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

Code of component.

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

Why does my 'git branch' have no master?

It seems there must be at least one local commit on the master branch to do:

git push -u origin master

So if you did git init . and then git remote add origin ..., you still need to do:

git add ...
git commit -m "..."

Hot deploy on JBoss - how do I make JBoss "see" the change?

Solution for Netbeans 8.02 and 8.1 IDE and JBOSS EAP 6.4:

  1. From the services tab of Netbeans, add JBOSS server to your "servers" node.
  2. If you are using MAVEN, netbeans compiles files and maven copies files to ./target directory. You need to create a symbolic link from .\target to JBOSS_HOME\standalone\deployments. Under windows, an example command would be

    cd %JBOSS_HOME%\standalone\deployments mklink /d MyWebApplication.war %PROJECTS_HOME%\MyWebApplication\target\MyWebApplication-1.0.0

    The above creates a symbolic link from %JBOSS_HOME%\standalone\deployments\MyWebApplication.war to \target\MyWebApplication-1.0.0 which is where maven transfers all files after compilation, or after a jsp, html or any other file changes.

  3. Last think to do is to create a CentralManagement.war.dodeploy file in %JBOSS_HOME%\standalone\deployments. This file will tell JBOSS to deploy the war "file" as a web application

How do I align a label and a textarea?

Just wrap the textarea with the label and set the textarea style to

vertical-align: middle;

Here is some magic for all textareas on the page:)

<style>
    label textarea{
        vertical-align: middle;
    }
</style>

<label>Blah blah blah Description: <textarea>dura bura</textarea></label>

Converting a year from 4 digit to 2 digit and back again in C#

//using java script
var curDate = new Date();
var curYear = curDate.getFullYear();
curYear = curYear.toString().slice(2);
document.write(curYear)
//using java script
//using sqlserver
select Right(Year(getDate()),2)
//using sql server
//Using c#.net 
DateTime dt = DateTime.Now;
            string curYear = dt.Year.ToString().Substring(2,2).ToString()  ;
//using c#.net

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

I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

Regular expression to extract URL from an HTML link

This works pretty well with using optional matches (prints after href=) and gets the link only. Tested on http://pythex.org/

(?:href=['"])([:/.A-z?<_&\s=>0-9;-]+)

Oputput:

Match 1. /wiki/Main_Page

Match 2. /wiki/Portal:Contents

Match 3. /wiki/Portal:Featured_content

Match 4. /wiki/Portal:Current_events

Match 5. /wiki/Special:Random

Match 6. //donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=en

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

std::queue iteration

I use something like this. Not very sophisticated but should work.

    queue<int> tem; 

    while(!q1.empty()) // q1 is your initial queue. 
    {
        int u = q1.front(); 

        // do what you need to do with this value.  

        q1.pop(); 
        tem.push(u); 
    }


    while(!tem.empty())
    {
        int u = tem.front(); 
        tem.pop(); 
        q1.push(u); // putting it back in our original queue. 
    }

It will work because when you pop something from q1, and push it into tem, it becomes the first element of tem. So, in the end tem becomes a replica of q1.

Private vs Protected - Visibility Good-Practice Concern

Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle: http://jsfiddle.net/NrnK5/

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

How can I detect window size with jQuery?

//get dimensions 
var height = $(window).height();
var width = $(window).width();

//refresh on resize
$(window).resize(function() {
  location.reload(true)
});

not sure if you wanted to tinker with the dimensions of elements or actually refresh the page. so here a bunch of different things pick what you want. you can even put the height and width in the resize event if you really wanted.

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

EditorFor() and html properties

I also had issue with setting the width of TextBox in MVC3, while setting the Clsss attribute worked for TextArea control but not for TextBoxFor control or EditorFor control:

I tried following & that worked for me:

@Html.TextBoxFor(model => model.Title, new { Class = "textBox", style = "width:90%;" })

also in this case Validations are working perfectly.

How to use TLS 1.2 in Java 6

You must create your own SSLSocketFactory based on Bouncy Castle. After to use it, pass to the common HttpsConnextion for using this customized SocketFactory.

1. First : Create a TLSConnectionFactory

Here one tips:

1.1 Extend SSLConnectionFactory

1.2 Override this method :

@Override 
public Socket createSocket(Socket socket, final String host, int port, boolean arg3)

This method will call the next internal method,

1.3 Implement an internal method _createSSLSocket(host, tlsClientProtocol);

Here you must create a Socket using TlsClientProtocol . The trick is override ...startHandshake() method calling TlsClientProtocol

 private SSLSocket _createSSLSocket(final String host , final TlsClientProtocol tlsClientProtocol) {
     return new SSLSocket() {    
       .... Override and implement SSLSocket methods,  particulary: 
            startHandshake() {
             }    
     }

     

Important : The full sample how to use TLS Client Protocol is well explained here: Using BouncyCastle for a simple HTTPS query

2. Second : Use this Customized SSLConnextionFactory on common HTTPSConnection.

This is important ! In other samples you can see into the web , u see hard-coded HTTP Commands....so with a customized SSLConnectionFactory u don't need nothing more...

  URL myurl = new URL( "http:// ...URL tha only Works in TLS 1.2);
  HttpsURLConnection  con = (HttpsURLConnection )myurl.openConnection();
  con.setSSLSocketFactory(new TSLSocketConnectionFactory());

Best way to "push" into C# array

I surggest using the CopyTo method, so here is my two cent on a solution that is easy to explain and simple. The CopyTo method copies the array to another array at a given index. In this case myArray is copied to newArr starting at index 1 so index 0 in newArr can hold the new value.

"Push" to array online demo

var newValue = 1;
var myArray = new int[5] { 2, 3, 4, 5, 6 };
var newArr = new int[myArray.Length + 1];

myArray.CopyTo(newArr, 1);
newArr[0] = newValue;
    
//debug
for(var i = 0; i < newArr.Length; i++){
    Console.WriteLine(newArr[i].ToString());
}

//output
1
2
3
4
5
6

jquery clone div and append it after specific div

try this out

$("div[id^='car']:last").after($('#car2').clone());

Disable pasting text into HTML form

from

Some may suggest using Javascript to capture the users' actions, like right-clicking the mouse or the Ctrl+C / Ctrl+V key combinations and then stopping the operation. But this is obviously not the best or simplest solution. The solution is integrated in the input field properties itself together with some event capturing using Javascript.

In order to disabled the browsers' autocomplete, simply add the attribute to the input field. It should look something like this:

<input type="text" autocomplete="off">

And if you want to deny Copy and Paste for that field, simply add the Javascript event capturing calls oncopy, onpaste, and oncut and make them return false, like so:

<input type="text" oncopy="return false;" onpaste="return false;" oncut="return false;">

The next step is using onselectstart to deny the input field's content selection from the user, but be warned: this only works for Internet Explorer. The rest of the above work great on all the major browsers: Internet Explorer, Mozilla Firefox, Apple Safari (on Windows OS, at least) and Google Chrome.

How to condense if/else into one line in Python?

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

Add new row to excel Table (VBA)

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

How to insert text with single quotation sql server 2005

INSERT INTO Table1 (Column1) VALUES ('John''s')

Or you can use a stored procedure and pass the parameter as -

usp_Proc1 @Column1 = 'John''s'

If you are using an INSERT query and not a stored procedure, you'll have to escape the quote with two quotes, else its OK if you don't do it.

The name 'ViewBag' does not exist in the current context

If you use Visual Studio 2013 and you like use MVC 3, you get this error because Visual Studio 2013 does not support MVC 3 natively (even of you change ./Views/web.config), only MVC 4: https://msdn.microsoft.com/en-us/library/hh266747.aspx

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

How to copy data from one table to another new table in MySQL?

This will do what you want:

INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1

If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.

I hope this helps.

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Flask ImportError: No Module Named Flask

in my case using Docker, my .env file was not copied, so the following env vars were not set:

.env.local: FLASK_APP=src/app.py

so in my Dockerfile i had to include:

FROM deploy as dev
COPY env ./env

which was referenced in docker-compose.yml

env_file: ./env/.env.local

another thing i had to pay attention to is the path variable to ensure my environment is used

ENV PATH $CONDA_DIR/envs/:my_environment_name_from_yml_file:/bin:$CONDA_DIR/bin:$PATH```

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

No you are not required to close anything BUT the connection. Per JDBC specs closing any higher object will automatically close lower objects. Closing Connection will close any Statements that connection has created. Closing any Statement will close all ResultSets that were created by that Statement. Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

Of course you might have long nested loops on the Connection creating lots of statements, then closing them is appropriate. I almost never close ResultSet though, seems excessive when closing Statement or Connection WILL close them.

Smooth GPS data

One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing

For example

Smoothing at five sample points A, B, C, D, E

ATOTAL = SUM of distances AB AC AD AE

BTOTAL = SUM of distances AB BC BD BE

CTOTAL = SUM of distances AC BC CD CE

DTOTAL = SUM of distances DA DB DC DE

ETOTAL = SUM of distances EA EB EC DE

If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }

This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.

How to check whether Kafka Server is running?

Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.

I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch sentence.

  def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
    props.put("group.id", kafkaParams.get("group.id").get.toString)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    val simpleConsumer = new KafkaConsumer[String, String](props)
    simpleConsumer.listTopics()
  }

Why shouldn't `&apos;` be used to escape single quotes?

If you really need single quotes, apostrophes, you can use

html    | numeric | hex
&lsquo; | &#145;  | &#x91; // for the left/beginning single-quote and
&rsquo; | &#146;  | &#x92; // for the right/ending single-quote

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me it was because I hadn't set an active class on any of the slides.

Unstaged changes left after git reset --hard

None of these methods worked for me, the only solution was to nuke the whole repo and re-clone it. This includes stashing, resetting, adding then resetting, clrf settings, case sensitivity etc. Sigh..

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

If you use android studio, this might be useful for you.

I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .

It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.

For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path

React.createElement: type is invalid -- expected a string

xxxxx.prototype = {
  dxxxx: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

You must add // eslint-disable-line react/forbid-prop-types, then it work!