Programs & Examples On #Pcmanfm

Could not find default endpoint element

In my case, I was referring to this service from a library project, not a startup Project. Once I copied <system.serviceModel> section to the configuration of the main startup project, The issue got resolved.

During running stage of any application, the configuration will be read from the startup/parent project instead of reading its own configurations mentioned in separate subprojects.

How to iterate over each string in a list of strings and operate on it's elements

The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
count = 0  
for i in words:  
     if i[0]==i[-1]:
        count = count + 1  
print(count)  

Output:

$python main.py
3

How to use GROUP BY to concatenate strings in MySQL?

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do:

SET group_concat_max_len=100000000;

and then, for example:

SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id

How to run Selenium WebDriver test cases in Chrome

You should download the chromeDriver in a folder, and add this folder in your PATH environment variable.

You'll have to restart your console to make it work.

Email Address Validation in Android on EditText

Java:

public static boolean isValidEmail(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}

Kotlin:

fun CharSequence?.isValidEmail() = !isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

Edit: It will work On Android 2.2+ onwards !!

Edit: Added missing ;

How do I kill an Activity when the Back button is pressed?

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}

My app closed with above code.

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

What's the difference between tilde(~) and caret(^) in package.json?

One liner explanation

The standard versioning system is major.minor.build (e.g. 2.4.1)

npm checks and fixes the version of a particular package based on these characters

~ : major version is fixed, minor version is fixed, matches any build number

e.g. : ~2.4.1 means it will check for 2.4.x where x is anything

^ : major version is fixed, matches any minor version, matches any build number

e.g. : ^2.4.1 means it will check for 2.x.x where x is anything

How do you send a Firebase Notification to all devices via CURL?

Check your topic list on firebase console.

  1. Go to firebase console

  2. Click Grow from side menu

  3. Click Cloud Messaging

  4. Click Send your first message

  5. In the notification section, type something for Notification title and Notification text

  6. Click Next

  7. In target section click Topic

  8. Click on Message topic textbox, then you can see your topics (I didn't created topic called android or ios, but I can see those two topics.

  9. When you send push notification add this as your condition.

    "condition"=> "'all' in topics || 'android' in topics || 'ios' in topics",

Full body

array(
    "notification"=>array(
        "title"=>"Test",
        "body"=>"Test Body",
    ),
    "condition"=> "'all' in topics || 'android' in topics || 'ios' in topics",
);

If you have more topics you can add those with || (or) condition, Then all users will get your notification. Tested and worked for me.

Difference between View and ViewGroup in Android

View is the SuperClass of All component like TextView, EditText, ListView, etc.. while ViewGroup is Collection of Views(TextView, EditText, ListView, etc..), somewhat like container.

Pass a data.frame column name to a function

This answer will cover many of the same elements as existing answers, but this issue (passing column names to functions) comes up often enough that I wanted there to be an answer that covered things a little more comprehensively.

Suppose we have a very simple data frame:

dat <- data.frame(x = 1:4,
                  y = 5:8)

and we'd like to write a function that creates a new column z that is the sum of columns x and y.

A very common stumbling block here is that a natural (but incorrect) attempt often looks like this:

foo <- function(df,col_name,col1,col2){
      df$col_name <- df$col1 + df$col2
      df
}

#Call foo() like this:    
foo(dat,z,x,y)

The problem here is that df$col1 doesn't evaluate the expression col1. It simply looks for a column in df literally called col1. This behavior is described in ?Extract under the section "Recursive (list-like) Objects".

The simplest, and most often recommended solution is simply switch from $ to [[ and pass the function arguments as strings:

new_column1 <- function(df,col_name,col1,col2){
    #Create new column col_name as sum of col1 and col2
    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column1(dat,"z","x","y")
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is often considered "best practice" since it is the method that is hardest to screw up. Passing the column names as strings is about as unambiguous as you can get.

The following two options are more advanced. Many popular packages make use of these kinds of techniques, but using them well requires more care and skill, as they can introduce subtle complexities and unanticipated points of failure. This section of Hadley's Advanced R book is an excellent reference for some of these issues.

If you really want to save the user from typing all those quotes, one option might be to convert bare, unquoted column names to strings using deparse(substitute()):

new_column2 <- function(df,col_name,col1,col2){
    col_name <- deparse(substitute(col_name))
    col1 <- deparse(substitute(col1))
    col2 <- deparse(substitute(col2))

    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column2(dat,z,x,y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is, frankly, a bit silly probably, since we're really doing the same thing as in new_column1, just with a bunch of extra work to convert bare names to strings.

Finally, if we want to get really fancy, we might decide that rather than passing in the names of two columns to add, we'd like to be more flexible and allow for other combinations of two variables. In that case we'd likely resort to using eval() on an expression involving the two columns:

new_column3 <- function(df,col_name,expr){
    col_name <- deparse(substitute(col_name))
    df[[col_name]] <- eval(substitute(expr),df,parent.frame())
    df
}

Just for fun, I'm still using deparse(substitute()) for the name of the new column. Here, all of the following will work:

> new_column3(dat,z,x+y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12
> new_column3(dat,z,x-y)
  x y  z
1 1 5 -4
2 2 6 -4
3 3 7 -4
4 4 8 -4
> new_column3(dat,z,x*y)
  x y  z
1 1 5  5
2 2 6 12
3 3 7 21
4 4 8 32

So the short answer is basically: pass data.frame column names as strings and use [[ to select single columns. Only start delving into eval, substitute, etc. if you really know what you're doing.

How to change the port number for Asp.Net core app?

All the other answer accounts only for http URLs. If the URL is https, then do as follows,

  1. Open launchsettings.json under Properties of the API project.

    enter image description here

  2. Change the sslPort under iisSettings -> iisExpress

A sample launchsettings.json will look as follows

{
  "iisSettings": {
    "iisExpress": {
      "applicationUrl": "http://localhost:12345",
      "sslPort": 98765 <== Change_This
    }
  },

how to customise input field width in bootstrap 3

<div class="form-group">
                    <div class="input-group col-md-5">
                    <div class="input-group-addon">
                    <span class="glyphicon glyphicon-envelope"></span> 
            </div>
                        <input class="form-control" type="text" name="text" placeholder="Enter Your Email Id" width="50px">

                    </div>
                    <input type="button" name="SIGNUP" value="SIGNUP">
            </div>

Powershell script to locate specific file/file name?

I use this form for just this sort of thing:

gci . hosts -r | ? {!$_.PSIsContainer}

. maps to positional parameter Path and "hosts" maps to positional parameter Filter. I highly recommend using Filter over Include if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include.

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

What's the whole point of "localhost", hosts and ports at all?

" In computer networking, a network host, Internet host, host, or Internet node is a computer connected to the Internet - or more generically - to any type of data network. A network host can host information resources as well as application software for providing network services. "-Wikipedia

Local host is a special name given to the local machine or that you are working on, ussually its IP Address is 127.0.0.1. However you can define it to be anything.

There are multiple Network services running on each host for example Apache/IIS( Http Web Server),Mail Clients, FTP clients etc. Each service has a specific port associated with it. You can think of it as this.

In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.

How can I get color-int from color resource?

You can use:

getResources().getColor(R.color.idname);

Check here on how to define custom colors:

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

EDIT(1): Since getColor(int id) is deprecated now, this must be used :

ContextCompat.getColor(context, R.color.your_color);

(added in support library 23)

EDIT(2):

Below code can be used for both pre and post Marshmallow (API 23)

ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme

Convert string to ASCII value python

If you are using python 3 or above,

>>> list(bytes(b'test'))
[116, 101, 115, 116]

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

Why doesn't git recognize that my file has been changed, therefore git add not working

It happend to me as well, I tried the above mentioned methods and nothing helped. Then the solution was to change the file via terminal, not GUI. I do not know why this worked but worked. After I edited the file via nano from terminal git recognized it as changed and i was able to add it and commit.

Use of min and max functions in C++

std::min and std::max are templates. So, they can be used on a variety of types that provide the less than operator, including floats, doubles, long doubles. So, if you wanted to write generic C++ code you'd do something like this:

template<typename T>
T const& max3(T const& a, T const& b, T const& c)
{
   using std::max;
   return max(max(a,b),c); // non-qualified max allows ADL
}

As for performance, I don't think fmin and fmax differ from their C++ counterparts.

Go / golang time.Now().UnixNano() convert to milliseconds?

As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.

See https://en.wikipedia.org/wiki/Dimensional_analysis

Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

Returning a file to View/Download in ASP.NET MVC

If, like me, you've come to this topic via Razor components as you're learning Blazor, then you'll find you need to think a little more outside of the box to solve this problem. It's a bit of a minefield if (also like me) Blazor is your first forray into the MVC-type world, as the documentation isn't as helpful for such 'menial' tasks.

So, at the time of writing, you cannot achieve this using vanilla Blazor/Razor without embedding an MVC controller to handle the file download part an example of which is as below:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

[Route("api/[controller]")]
[ApiController]
public class FileHandlingController : ControllerBase
{
    [HttpGet]
    public FileContentResult Download(int attachmentId)
    {
        TaskAttachment taskFile = null;

        if (attachmentId > 0)
        {
            // taskFile = <your code to get the file>
            // which assumes it's an object with relevant properties as required below

            if (taskFile != null)
            {
                var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = taskFile.Filename
                };

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
            }
        }

        return new FileContentResult(taskFile?.FileData, taskFile?.FileContentType);
    }
}

Next, make sure your application startup (Startup.cs) is configured to correctly use MVC and has the following line present (add it if not):

        services.AddMvc();

.. and then finally modify your component to link to the controller, for example (iterative based example using a custom class):

    <tbody>
        @foreach (var attachment in yourAttachments)
        {
        <tr>
            <td><a href="api/[email protected]" target="_blank">@attachment.Filename</a> </td>
            <td>@attachment.CreatedUser</td>
            <td>@attachment.Created?.ToString("dd MMM yyyy")</td>
            <td><ul><li class="oi oi-circle-x delete-attachment"></li></ul></td>
        </tr>
        }
        </tbody>

Hopefully this helps anyone who struggled (like me!) to get an appropriate answer to this seemingly simple question in the realms of Blazor…!

Primary key or Unique index?

Foreign keys work with unique constraints as well as primary keys. From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table

For transactional replication, you need the primary key. From Books Online:

Tables published for transactional replication must have a primary key. If a table is in a transactional replication publication, you cannot disable any indexes that are associated with primary key columns. These indexes are required by replication. To disable an index, you must first drop the table from the publication.

Both answers are for SQL Server 2005.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Two reasons for Stale element

  1. An element that is found on a web page referenced as a WebElement in WebDriver then the DOM changes (probably due to JavaScript functions) that WebElement goes stale.

  2. The element has been deleted entirely.

When you try to interact with the staled WebElement[any above case], the StaleElementException is thrown.

How to avoid/resolve Stale Exception?

  1. Storing locators to your elements instead of references
driver = webdriver.Firefox();
driver.get("http://www.github.com");
search_input = lambda: driver.find_element_by_name('q');
search_input().send_keys('hello world\n'); 
time.sleep(5);


search_input().send_keys('hello frank\n') // no stale element exception
  1. Leverage hooks in the JS libraries used
   # Using Jquery queue to get animation queue length.
    animationQueueIs = """
    return $.queue( $("#%s")[0], "fx").length;
    """ % element_id
    wait_until(lambda: self.driver.execute_script(animationQueueIs)==0)
  1. Moving your actions into JavaScript injection
 self.driver.execute_script("$(\"li:contains('Narendra')\").click()");
  1. Proactively wait for the element to go stale
  # Wait till the element goes stale, this means the list has updated
  wait_until(lambda: is_element_stale(old_link_reference))

This solution, which worked for me, I have mentioned here if you have any additional scenario, which worked for you then comment below

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

How can I specify a branch/tag when adding a Git submodule?

An example of how I use Git submodules.

  1. Create a new repository
  2. Then clone another repository as a submodule
  3. Then we have that submodule use a tag called V3.1.2
  4. And then we commit.

And that looks a little bit like this:

git init 
vi README
git add README
git commit 
git submodule add git://github.com/XXXXX/xxx.yyyy.git stm32_std_lib
git status

git submodule init
git submodule update

cd stm32_std_lib/
git reset --hard V3.1.2 
cd ..
git commit -a

git submodule status 

Maybe it helps (even though I use a tag and not a branch)?

How to install "ifconfig" command in my ubuntu docker image?

In case you want to use the Docker image as a "regular" Ubuntu installation, you can also run unminimize. This will install a lot more than ifconfig, so this might not be what you want.

How to prevent "The play() request was interrupted by a call to pause()" error?

Solutions proposed here either didn't work for me or where to large, so I was looking for something else and found the solution proposed by @dighan on bountysource.com/issues/

So here is the code that solved my problem:

var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
    playPromise.catch(() => { media.play(); })
}

It still throws an error into console, but at least the video is playing :)

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

function is not defined error in Python

It works for me:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

Make sure you define the function before you call it.

React router nav bar example

Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.

Nav.js

  import React from 'react';
  import { Link } from 'react-router';

  export default class Nav extends React.Component {
    render() {    
      return (
        <nav className="Nav">
          <div className="Nav__container">
            <Link to="/" className="Nav__brand">
              <img src="logo.svg" className="Nav__logo" />
            </Link>

            <div className="Nav__right">
              <ul className="Nav__item-wrapper">
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path1">Link 1</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path2">Link 2</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path3">Link 3</Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
      );
    }
  }

App.js

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
            <div>
              <Nav />
              <Switch>
                <Route exactly component={Landing} pattern="/" />
                <Route exactly component={Page1} pattern="/path1" />
                <Route exactly component={Page2} pattern="/path2" />
                <Route exactly component={Page3} pattern="/path3" />
                <Route component={Page404} />
              </Switch>
            </div>
          </Router>
        </div>
      );
    }
  }

Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar

Edit

A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
      <div>
        <Header/>
        <Component {...props}/>
      </div>
    )}/>
  )

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
              <Switch>
                <NavRoute exactly component={Landing} pattern="/" />
                <Route exactly component={Login} pattern="/login" />
                <NavRoute exactly component={Page1} pattern="/path1" />
                <NavRoute exactly component={Page2} pattern="/path2" />
                <NavRoute component={Page404} />
              </Switch>
          </Router>
        </div>
      );
    }
  }

Any way to select without causing locking in MySQL?

another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 

Find when a file was deleted in Git

Try:

git log --stat | grep file

Eclipse Java Missing required source folder: 'src'

Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.

good luck!

'list' object has no attribute 'shape'

firstly u have to import numpy library (refer code for making a numpy array) shape only gives the output only if the variable is attribute of numpy library .in other words it must be a np.array or any other data structure of numpy. Eg.

`>>> import numpy
>>> a=numpy.array([[1,1],[1,1]])
>>> a.shape
(2, 2)`

Add button to navigationbar programmatically

Simple use native editBarButton like this

self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.navigationItem.rightBarButtonItem setAction:@selector(editBarBtnPressed)];

and then

- (void)editBarBtnPressed {
    if ([infoTable isEditing]) {
        [self.editButtonItem setTitle:@"Edit"];
        [infoTable setEditing:NO animated:YES];
    }
    else {
        [self.editButtonItem setTitle:@"Done"];
        [infoTable setEditing:YES animated:YES];
    }
}

Have fun...!!!

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

I had the same issue, and I tried everything what is posted here to fix it but none worked for me. In my case I'm using Cygwin to compile the dll. It seems that JVM tries to find the JRE DLLs in the virtual Cygwin path. I added the the Cygwin's virtual directory path to JRE's DLLs and it works now. I did something like:

SET PATH="/cygdrive/c/Program Files/Java/jdk1.8.0_45";%PATH%

IN vs OR in the SQL WHERE Clause

The OR operator needs a much more complex evaluation process than the IN construct because it allows many conditions, not only equals like IN.

Here is a like of what you can use with OR but that are not compatible with IN: greater. greater or equal, less, less or equal, LIKE and some more like the oracle REGEXP_LIKE. In addition consider that the conditions may not always compare the same value.

For the query optimizer it's easier to to manage the IN operator because is only a construct that defines the OR operator on multiple conditions with = operator on the same value. If you use the OR operator the optimizer may not consider that you're always using the = operator on the same value and, if it doesn't perform a deeper and very much more complex elaboration, it could probably exclude that there may be only = operators for the same values on all the involved conditions, with a consequent preclusion of optimized search methods like the already mentioned binary search.

[EDIT] Probably an optimizer may not implement optimized IN evaluation process, but this doesn't exclude that one time it could happen(with a database version upgrade). So if you use the OR operator that optimized elaboration will not be used in your case.

Is it really impossible to make a div fit its size to its content?

CSS display setting

It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:

  • display: inline-block - this is the one you're not aware of

  • position: absolute

  • float: left/right

Arraylist swap elements

You can use Collections.swap(List<?> list, int i, int j);

Is there a way to run Bash scripts on Windows?

After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a "full" bash environment by using the MinGW Git bash shell.

I am not a great fan of Cygwin (yes I am sure it's really powerful), so running bash scripts on windows without having to install it perfect for me.

How do I change the font size and color in an Excel Drop Down List?

I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

How to use JUnit to test asynchronous processes

This is what I'm using nowadays if the test result is produced asynchronously.

public class TestUtil {

    public static <R> R await(Consumer<CompletableFuture<R>> completer) {
        return await(20, TimeUnit.SECONDS, completer);
    }

    public static <R> R await(int time, TimeUnit unit, Consumer<CompletableFuture<R>> completer) {
        CompletableFuture<R> f = new CompletableFuture<>();
        completer.accept(f);
        try {
            return f.get(time, unit);
        } catch (InterruptedException | TimeoutException e) {
            throw new RuntimeException("Future timed out", e);
        } catch (ExecutionException e) {
            throw new RuntimeException("Future failed", e.getCause());
        }
    }
}

Using static imports, the test reads kinda nice. (note, in this example I'm starting a thread to illustrate the idea)

    @Test
    public void testAsync() {
        String result = await(f -> {
            new Thread(() -> f.complete("My Result")).start();
        });
        assertEquals("My Result", result);
    }

If f.complete isn't called, the test will fail after a timeout. You can also use f.completeExceptionally to fail early.

Jackson: how to prevent field serialization

Illustrating what StaxMan has stated, this works for me

private String password;

@JsonIgnore
public String getPassword() {
    return password;
}

@JsonProperty
public void setPassword(String password) {
    this.password = password;
}

Date Conversion from String to sql Date in Java giving different output?

mm is minutes. You want MM for months:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Don't feel bad - this exact mistake comes up a lot.

ORDER BY the IN value list

To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.

In that way, you explicitly describe the ordering you desire in the database, where it should be.

How can I get query string values in JavaScript?

Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));

IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL.

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.

How to sort by dates excel?

If you dont want to format a separate column with you normal dates pasted to it -- do the following -- add a column to the extreme left of your data and reverve your date ie if the date you had already entered was for example 11.5.16 enter int he new lefthand column 160511 ( notice that there are numbers only and no full stops . When you now sort there will be no mix ups as you have encountered.i have used this method for over 30 years and it never lets me down. And as you have placed the date by year, month and day you neednt include that column if you want or need tu print out your complete list.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

Serialize and Deserialize Json and Json Array in Unity

Like @Maximiliangerhardt said, MiniJson do not have the capability to deserialize properly. I used JsonFx and works like a charm. Works with the []

player[] p = JsonReader.Deserialize<player[]>(serviceData);
Debug.Log(p[0].playerId +" "+ p[0].playerLoc+"--"+ p[1].playerId + " " + p[1].playerLoc+"--"+ p[2].playerId + " " + p[2].playerLoc);

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Download and install an ipa from self hosted url on iOS

There are online tools that simplify this process of sharing, for example https://abbashare.com or https://diawi.com Create an ipa file from xcode with adhoc or inhouse profile, and upload this file on these site. I prefer abbashare because save file on your dropbox and you can delete it whenever you want

Android ADB devices unauthorized

In Android studio, Run menu > Run shows OFFLINE ... for the connected device.

Below is the procedure followed to solve it:

  1. (Read the below note first) Delete the ~/.android/adbkey (or, rename to ~/.android/adbkey2, this is even better incase you want it back for some reason)
    Note: I happened to do this step, but it didn't solve the problem, after doing all the below steps it worked, so unsure if this step is required.

  2. Run locate platform-tools/adb
    Note: use the path that comes from here in below commands

  3. Kill adb server:
    sudo ~/Android/Sdk/platform-tools/adb kill-server

  4. You will get a Allow accept.. message popup on your device. Accept it. This is important, which solves the problem.

  5. Start adb server:
    sudo ~/Android/Sdk/platform-tools/adb start-server

  6. In Android studio, do Run menu > Run again
    It will show something like Samsung ... (your phone manufacture name).
    Also installs the apk on device correctly this time without error.

Hope that helps.

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

jQuery disable/enable submit button

Vanilla JS Solution. It works for a whole form not only one input.

In question selected JavaScript tag.

HTML Form:

_x000D_
_x000D_
var form = document.querySelector('form')_x000D_
    var inputs = form.querySelectorAll('input')_x000D_
    var required_inputs = form.querySelectorAll('input[required]')_x000D_
    var register = document.querySelector('input[type="submit"]')_x000D_
    form.addEventListener('keyup', function(e) {_x000D_
        var disabled = false_x000D_
        inputs.forEach(function(input, index) {_x000D_
            if (input.value === '' || !input.value.replace(/\s/g, '').length) {_x000D_
                disabled = true_x000D_
            }_x000D_
        })_x000D_
        if (disabled) {_x000D_
            register.setAttribute('disabled', 'disabled')_x000D_
        } else {_x000D_
            register.removeAttribute('disabled')_x000D_
        }_x000D_
    })
_x000D_
<form action="/signup">_x000D_
        <div>_x000D_
            <label for="username">User Name</label>_x000D_
            <input type="text" name="username" required/>_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="password">Password</label>_x000D_
            <input type="password" name="password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="r_password">Retype Password</label>_x000D_
            <input type="password" name="r_password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="email">Email</label>_x000D_
            <input type="text" name="email" />_x000D_
        </div>_x000D_
        <input type="submit" value="Signup" disabled="disabled" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Some explanation:

In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.

If you need to disable submit button until all required input fields are filled in - replace:

inputs.forEach(function(input, index) {

with:

required_inputs.forEach(function(input, index) {

where required_inputs is already declared array containing only required input fields.

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

WooCommerce - get category for product page

Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php

Hope it helps others.

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
    function woo_post_meta( ) {
        global $woo_options;
        global $post;

        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $product_cat = $term->name;
            break;
        }

?>
<aside class="post-meta">
    <ul>
        <li class="post-category">
            <?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>

        </li>
        <?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
        <?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
            <li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
        <?php } ?>
        <?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
    </ul>
</aside>
<?php
    }
}


?>

HashMap - getting First Key value

Also a nice way of doing this :)

Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

Another nice one: Accidentally redefining modules. I copy/pasted stuff a little too eagerly earlier today and ended up having a module definition somewhere, that I overrode with my controller definitions:

// controllers.js - dependencies in one place, perfectly fine
angular.module('my.controllers', [/* dependencies */]);

Then in my definitions, I was supposed to reference it like so:

// SomeCtrl.js - grab the module, add the controller
angular.module('my.controllers')
 .controller('SomeCtrl', function() { /* ... */ });

What I did instead, was:

// Do not try this at home!

// SomeCtrl.js
angular.module('my.controllers', []) // <-- redefined module, no harm done yet
  .controller('SomeCtrl', function() { /* ... */ });

// SomeOtherCtrl.js
angular.module('my.controllers', []) // <-- redefined module - SomeCtrl no longer accessible
  .controller('SomeOtherCtrl', function() { /* ... */ });

Note the extra bracket in the call to angular.module.

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Remove accents/diacritics in a string in JavaScript

Pass a user defined function to the Array.sort() method, and in this user defined function use String.localeCompare()

function myCompareFunction(a, b) {
  return a.localeCompare(b);
}

var values = ["pêches", "épinards", "tomates", "fraises"];

// WRONG: ["fraises", "pêches", "tomates", "épinards"]
values.sort();

 // **GOOD**: ["épinards", "fraises", "pêches", "tomates"]
values.sort(myCompareFunction);

Hide all elements with class using plain Javascript

I use a modified version of this:

function getElementsByClass(nameOfClass) {    
  var temp, all, elements;

  all = document.getElementsByTagName("*");
  elements = [];

  for(var a=0;a<all.length;a++) {
    temp = all[a].className.split(" ");
    for(var b=0;b<temp.length;b++) {
      if(temp[b]==nameOfClass) { 
        elements.push(ALL[a]); 
        break; 
      }
    }
  }
  return elements;
};

And JQuery will do this really easily too.

Response Content type as CSV

In ASP.net MVC, you can use a FileContentResult and the File method:

public FileContentResult DownloadManifest() {
    byte[] csvData = getCsvData();
    return File(csvData, "text/csv", "filename.csv");
}

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

I had problems triggering focus on an element (a form input) that was transitioning into the page. I found it was fixable by invoking the focus event from inside a setTimeout with no delay on it. As I understand it (from, eg. this answer), this delays the function until the current execution queue finishes, so in this case it delays the focus event until the transition has completed.

setTimeout(function(){
    $('#goal-input').focus();
});

console.log(result) returns [object Object]. How do I get result.name?

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}

Using Default Arguments in a Function

In PHP 8 we can use named arguments for this problem.

So we could solve the problem described by the original poster of this question:

What if I want to use the default argument for $x and set a different argument for $y?

With:

foo(blah: "blah", y: "test");

Reference: https://wiki.php.net/rfc/named_params (in particular the "Skipping defaults" section)

Filtering Table rows using Jquery

tr:not(:contains(.... work for me

function busca(busca){
    $("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
    $("#listagem tr:contains('"+busca+"')").css("display", "");
}

Reset push notification settings for app

As ianolito said, setting the date should work:

You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on.

I noticed on my device (iPhone 4, iOS 6.1.2) setting the system clock a day forward or even a few days did not work for me. So I set the date forward a month and then it did work and my application showed the notifications prompt again.

Hope this helps for anyone, it can be kind of head aching!

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

First, you should use pip install, and then download another package in http://www.graphviz.org/Download_windows.php and add the install location into the environmental path, then it works.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

Min and max value of input in angular4 application

If you are looking to validate length use minLength and maxLength instead.

How to set web.config file to show full error message

This can also help you by showing full details of the error on a client's browser.

<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>

How can I stop redis-server?

Following worked for me on MAC

 ps aux | grep 'redis-server' | awk '{print $2}' | xargs sudo kill -9

jQuery Call to WebService returns "No Transport" error

I solved it simply by removing the domain from the request url.

Before: https://some.domain.com/_vti_bin/service.svc

After: /_vti_bin/service.svc

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

The three operators have related but different meanings, despite the misleading note from the IDE.

The :: operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.

The . and -> operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).

The this object is always a pointer to the current instance, hence why the -> operator is the only one that works.

Examples:

// In a header file
namespace Namespace {
    class Class {
        private:
            int x;
        public:
            Class() : x(4) {}
            void incrementX();
    };
}

// In an implementation file
namespace Namespace {
    void Class::incrementX() {    // Using scope resolution to get to the class member when we aren't using an instance
        ++(this->x);              // this is a pointer, so using ->. Equivalent to ++((*this).x)
    }
}

// In a separate file lies your main method
int main() {
    Namespace::Class myInstance;   // instantiates an instance. Note the scope resolution
    Namespace::Class *myPointer = new Namespace::Class;
    myInstance.incrementX();       // Calling a function on an object instance.
    myPointer->incrementX();       // Calling a function on an object pointer.
    (*myPointer).incrementX();     // Calling a function on an object pointer by dereferencing first

    return 0;
}

How to disable/enable a button with a checkbox if checked

HTML

<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

JS

var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
  sendbtn.disabled = !!this.checked;
};

DEMO

How can I regenerate ios folder in React Native project?

As @Alok mentioned in the comments, you can do react-native eject to generate the ios and android folders. But you will need an app.json in your project first.

{"name": "example", "displayName": "Example"}

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

Append value to empty vector in R?

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

PNG supports alphachannel transparency.

TIFF can have extended options I.e. Geo referencing for GIS applications.

I recommend only ever using JPEG for photographs, never for images like clip art, logos, text, diagrams, line art.

Favor PNG.

How can I get a Bootstrap column to span multiple rows?

For Bootstrap 3:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="row">_x000D_
    <div class="col-md-4">_x000D_
        <div class="well">1_x000D_
            <br/>_x000D_
            <br/>_x000D_
            <br/>_x000D_
            <br/>_x000D_
            <br/>_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="col-md-8">_x000D_
        <div class="row">_x000D_
            <div class="col-md-6">_x000D_
                <div class="well">2</div>_x000D_
            </div>_x000D_
            <div class="col-md-6">_x000D_
                <div class="well">3</div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="row">_x000D_
            <div class="col-md-6">_x000D_
                <div class="well">4</div>_x000D_
            </div>_x000D_
            <div class="col-md-6">_x000D_
                <div class="well">5</div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="row">_x000D_
    <div class="col-md-4">_x000D_
        <div class="well">6</div>_x000D_
    </div>_x000D_
    <div class="col-md-4">_x000D_
        <div class="well">7</div>_x000D_
    </div>_x000D_
    <div class="col-md-4">_x000D_
        <div class="well">8</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

For Bootstrap 2:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="row-fluid">_x000D_
    <div class="span4"><div class="well">1<br/><br/><br/><br/><br/></div></div>_x000D_
    <div class="span8">_x000D_
        <div class="row-fluid">_x000D_
            <div class="span6"><div class="well">2</div></div>_x000D_
            <div class="span6"><div class="well">3</div></div>_x000D_
        </div>_x000D_
        <div class="row-fluid">_x000D_
            <div class="span6"><div class="well">4</div></div>_x000D_
            <div class="span6"><div class="well">5</div></div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="row-fluid">_x000D_
    <div class="span4">_x000D_
        <div class="well">6</div>_x000D_
    </div>_x000D_
    <div class="span4">_x000D_
        <div class="well">7</div>_x000D_
    </div>_x000D_
    <div class="span4">_x000D_
        <div class="well">8</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See the demo on JSFiddle (Bootstrap 2): http://jsfiddle.net/SxcqH/52/

Clear the entire history stack and start a new activity on Android

I found too simple hack just do this add new element in AndroidManifest as:-

<activity android:name=".activityName"
          android:label="@string/app_name"
          android:noHistory="true"/>

the android:noHistory will clear your unwanted activity from Stack.

ASP.NET MVC: What is the purpose of @section?

It lets you define a @Section of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.

//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);

Hope this helps.

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

Passing array in GET for a REST call

This worked for me.

/users?ids[]=id1&ids[]=id2

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

Email & Phone Validation in Swift

Swift 4 & Swift 5:

func isValidPhone(phone: String) -> Bool {
        let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phone)
    }

func isValidEmail(email: String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: email)
    }

how to query for a list<String> in jdbctemplate

You can't use placeholders for column names, table names, data type names, or basically anything that isn't data.

How can I use a C++ library from node.js?

Try shelljs to call c/c++ program or shared libraries by using node program from linux/unix . node-cmd an option in windows. Both packages basically enable us to call c/c++ program similar to the way we call from terminal/command line.

Eg in ubuntu:

const shell = require('shelljs');

shell.exec("command or script name");

In windows:

const cmd = require('node-cmd');
cmd.run('command here');

Note: shelljs and node-cmd are for running os commands, not specific to c/c++.

How to remove all duplicate items from a list

There is a faster way to fix this:

list = [1, 1.0, 1.41, 1.73, 2, 2, 2.0, 2.24, 3, 3, 4, 4, 4, 5, 6, 6, 8, 8, 9, 10]
list2=[]

for value in list:
    try:
        list2.index(value)
    except:
        list2.append(value)
list.clear()
for value in list2:
    list.append(value)
list2.clear()
print(list)
print(list2)

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

If you have an issue, you need to locate your pg_hba.conf. The command is:

find / -name 'pg_hba.conf' 2>/dev/null

and after that change the configuration file:

Postgresql 9.3

Postgresql 9.3

Postgresql 9.4

Postgresql 9.3

The next step is: Restarting your db instance:

service postgresql-9.3 restart

If you have any problems, you need to set password again:

ALTER USER db_user with password 'db_password';

Darken background image on hover

you can use this:

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

as seen on: https://stackoverflow.com/a/24084708/8953378

Android Material and appcompat Manifest merger failed

In my case, this is working perfectly.. I have added below two line codes inside manifest file

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

Credit goes to this answer.

Manifest file Example

Check, using jQuery, if an element is 'display:none' or block on click

$("element").filter(function() { return $(this).css("display") == "none" });

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

Generate list of all possible permutations of a string

import java.util.*;

public class all_subsets {
    public static void main(String[] args) {
        String a = "abcd";
        for(String s: all_perm(a)) {
            System.out.println(s);
        }
    }

    public static Set<String> concat(String c, Set<String> lst) {
        HashSet<String> ret_set = new HashSet<String>();
        for(String s: lst) {
            ret_set.add(c+s);
        }
        return ret_set;
    }

    public static HashSet<String> all_perm(String a) {
        HashSet<String> set = new HashSet<String>();
        if(a.length() == 1) {
            set.add(a);
        } else {
            for(int i=0; i<a.length(); i++) {
                set.addAll(concat(a.charAt(i)+"", all_perm(a.substring(0, i)+a.substring(i+1, a.length()))));
            }
        }
        return set;
    }
}

Rules for C++ string literals escape character

Control characters:

(Hex codes assume an ASCII-compatible character encoding.)

  • \a = \x07 = alert (bell)
  • \b = \x08 = backspace
  • \t = \x09 = horizonal tab
  • \n = \x0A = newline (or line feed)
  • \v = \x0B = vertical tab
  • \f = \x0C = form feed
  • \r = \x0D = carriage return
  • \e = \x1B = escape (non-standard GCC extension)

Punctuation characters:

  • \" = quotation mark (backslash not required for '"')
  • \' = apostrophe (backslash not required for "'")
  • \? = question mark (used to avoid trigraphs)
  • \\ = backslash

Numeric character references:

  • \ + up to 3 octal digits
  • \x + any number of hex digits
  • \u + 4 hex digits (Unicode BMP, new in C++11)
  • \U + 8 hex digits (Unicode astral planes, new in C++11)

\0 = \00 = \000 = octal ecape for null character

If you do want an actual digit character after a \0, then yes, I recommend string concatenation. Note that the whitespace between the parts of the literal is optional, so you can write "\0""0".

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Regex for parsing directory and filename

Try this:

^(.+)\/([^\/]+)$

EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex

What design patterns are used in Spring framework?

Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.

How to redirect from one URL to another URL?

You can redirect anything or more URL via javascript, Just simple window.location.href with if else

Use this code,

<script>
if(window.location.href == 'old_url')
{
    window.location.href="new_url";
}


//Another url redirect
if(window.location.href == 'old_url2')
{
    window.location.href="new_url2";
}
</script>

You can redirect many URL's by this procedure. Thanks.

How to see data from .RData file?

isfar<-load("C:/Users/isfar.RData") 
if(is.data.frame(isfar)){
   names(isfar)
}

If isfar is a dataframe, this will print out the names of its columns.

How to compare strings in sql ignoring case?

If you are matching the full value of the field use

WHERE UPPER(fieldName) = 'ANGEL'

EDIT: From your comment you want to use:

SELECT 
    RPAD(a.name, 10,'=') "Nombre del Cliente"
    , RPAD(b.name, 12,'*') "Nombre del Consumidor" 
FROM 
    s_customer a, 
    s_region b 
WHERE 
    a.region_id = b.id 
    AND UPPER(a.name) LIKE '%SPORT%' 

How to get the type of T from a member of a generic class or method?

If you dont need the whole Type variable and just want to check the type you can easily create a temp variable and use is operator.

T checkType = default(T);

if (checkType is MyClass)
{}

How do I center list items inside a UL element?

A more modern way is to use flexbox:

_x000D_
_x000D_
ul{_x000D_
  list-style-type:none;_x000D_
  display:flex;_x000D_
  justify-content: center;_x000D_
_x000D_
}_x000D_
ul li{_x000D_
  display: list-item;_x000D_
  background: black;_x000D_
  padding: 5px 10px;_x000D_
  color:white;_x000D_
  margin: 0 3px;_x000D_
}_x000D_
div{_x000D_
  background: wheat;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
  <li>One</li>_x000D_
  <li>Two</li>_x000D_
  <li>Three</li>_x000D_
</ul>  _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show special characters in Unix while using 'less' Command

Now, sometimes you already have less open, and you can't use cat on it. For example, you did a | less, and you can't just reopen a file, as that's actually a stream.

If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$. The search will highlight the last character, even if it is a blank, making it easy to identify it.

That will only help with the end of line case. If you need other special characters, you can use the cat -vet solution above with marks and pipe:

  • mark the top of the text you're interested in: ma
  • go to the bottom of the text you're interested in and mark it, as well: mb
  • go back to the mark a: 'a
  • pipe from a to b through cat -vet and view the result in another less command: |bcat -vet | less

This will open another less process, which shows the result of running cat -vet on the text that lies between marks a and b.

If you want the whole thing, instead, do g|$cat -vet | less, to go to the first line and filter all lines through cat.

The advantage of this method over less options is that it does not mess with the output you see on the screen.

One would think that eight years after this question was originally posted, less would have that feature... But I can't even see a feature request for it on https://github.com/gwsw/less/issues

What's a decent SFTP command-line client for windows?

www.bitvise.com - sftpc is a good command line client also.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

process.env.NODE_ENV is adding a white space do this

process.env.NODE_ENV.trim() == 'production'

Text in a flex container doesn't wrap in IE11

Hi for me I had to apply the 100% width to its grandparent element. Not its child element(s).

.grandparent {
    float:left;
    clear: both;
    width:100%; //fix for IE11 text overflow
}

.parent {
    display: flex;
    border: 1px solid red;
    align-items: center;
}

.child {
    border: 1px solid blue;
}

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

Converting an object to a string

If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.

var obj = {
  name: 'myObj'
};
dojo.toJson(obj);

which will return a string. If you want to convert the object to json data then add a second parameter of true.

dojo.toJson(obj, true);

http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson

How to get certain commit from GitHub project

Instead of navigating through the commits, you can also hit the y key (Github Help, Keyboard Shortcuts) to get the "permalink" for the current revision / commit.
This will change the URL from https://github.com/<user>/<repository> (master / HEAD) to https://github.com/<user>/<repository>/tree/<commit id>.

In order to download the specific commit, you'll need to reload the page from that URL, so the Clone or Download button will point to the "snapshot" https://github.com/<user>/<repository>/archive/<commit id>.zip instead of the latest https://github.com/<user>/<repository>/archive/master.zip.

How to escape a while loop in C#

"break" is a command that breaks out of the "closest" loop.

While there are many good uses for break, you shouldn't use it if you don't have to -- it can be seen as just another way to use goto, which is considered bad.

For example, why not:

while (!(the condition you're using to break))
        {
         //Your code here.
        }

If the reason you're using "break" is because you don't want to continue execution of that iteration of the loop, you may want to use the "continue" keyword, which immediately jumps to the next iteration of the loop, whether it be while or for.

while (!condition) {
   //Some code
   if (condition) continue;
   //More code that will be skipped over if the condition was true
}

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to get height and width of device display in angular2 using typescript?

For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

  • Step 1:

In that Component do: import { HostListener } from "@angular/core";

  • Step 2:

In the component's class body write:

@HostListener('window:resize', ['$event'])
onResize(event?) {
   this.screenHeight = window.innerHeight;
   this.screenWidth = window.innerWidth;
}
  • Step 3:

In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

constructor() {
  this.onResize();
}    

Complete code:

import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class FooComponent implements OnInit {
    screenHeight: number;
    screenWidth: number;

    constructor() {
        this.getScreenSize();
    }

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.screenHeight = window.innerHeight;
          this.screenWidth = window.innerWidth;
          console.log(this.screenHeight, this.screenWidth);
    }

}

XSL substring and indexOf

I wrote my own index-of function, inspired by strpos() in PHP.

<xsl:function name="fn:strpos">
    <xsl:param name="haystack"/>
    <xsl:param name="needle"/>
    <xsl:value-of select="fn:_strpos($haystack, $needle, 1, string-length($haystack) - string-length($needle))"/>
</xsl:function>

<xsl:function name="fn:_strpos">
    <xsl:param name="haystack"/>
    <xsl:param name="needle"/>
    <xsl:param name="pos"/>
    <xsl:param name="count"/>
    <xsl:choose>
        <xsl:when test="$count &lt; 0">
            <!-- Not found. Most common is to return -1 here (or maybe 0 in XSL?). -->
            <!-- But this way, the result can be used with substring() without checking. -->
            <xsl:value-of select="string-length($haystack) + 1"/>
        </xsl:when>
        <xsl:when test="starts-with(substring($haystack, $pos), $needle)">
            <xsl:value-of select="$pos"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="fn:_strpos($haystack, $needle, $pos + 1, $count - 1)"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:function>

Using getResources() in non-activity class

Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

Changing CSS Values with Javascript

Perhaps try this:

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

Rebasing remote branches in Git

Because you rebased feature on top of the new master, your local feature is not a fast-forward of origin/feature anymore. So, I think, it's perfectly fine in this case to override the fast-forward check by doing git push origin +feature. You can also specify this in your config

git config remote.origin.push +refs/heads/feature:refs/heads/feature

If other people work on top of origin/feature, they will be disturbed by this forced update. You can avoid that by merging in the new master into feature instead of rebasing. The result will indeed be a fast-forward.

Cannot authenticate into mongo, "auth fails"

It appears the problem is that a user created via the method described in the mongo docs does not have permission to connect to the default database (test), even if that user was created with the "userAdminAnyDatabase" and "dbAdminAnyDatabase" roles.

WHERE Clause to find all records in a specific month

SELECT * FROM yourtable WHERE yourtimestampfield LIKE 'AAAA-MM%';

Where AAAA is the year you want and MM is the month you want

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

How to suspend/resume a process in Windows?

You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).

Hard Way

First get all the threads of a given process then call the SuspendThread function to stop each one (and ResumeThread to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.

void suspend(DWORD processId)
{
    HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    THREADENTRY32 threadEntry; 
    threadEntry.dwSize = sizeof(THREADENTRY32);

    Thread32First(hThreadSnapshot, &threadEntry);

    do
    {
        if (threadEntry.th32OwnerProcessID == processId)
        {
            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
                threadEntry.th32ThreadID);

            SuspendThread(hThread);
            CloseHandle(hThread);
        }
    } while (Thread32Next(hThreadSnapshot, &threadEntry));

    CloseHandle(hThreadSnapshot);
}

Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.

Undocumented way

Starting from Windows XP there is the NtSuspendProcess but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).

typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);

void suspend(DWORD processId)
{
    HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));

    NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
        GetModuleHandle("ntdll"), "NtSuspendProcess");

    pfnNtSuspendProcess(processHandle);
    CloseHandle(processHandle);
}

"Debugger" Way

To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop.

This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.

void suspend(DWORD processId)
{
    DebugActiveProcess(processId);
}

From Command Line

As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:

Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)

Of course if you need it often you can make an alias for that.

XAMPP on Windows - Apache not starting

I was able to fix this!

Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.

I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.

The fix. Make sure you backup your system first!

  1. Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc)

  2. Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.

    a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'

    b. on command prompt type sc delete service, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"

    c. press enter. Now refresh or close/open your services window and you'll see it`s gone.

DO THIS for all services that XAMPP finds as running with an incorrect path.

Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts

Find all files with a filename beginning with a specified string?

Use find with a wildcard:

find . -name 'mystring*'

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use

arr.join("");

C library function to perform sort

C/C++ standard library <stdlib.h> contains qsort function.

This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:

qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);

The only thing that you need to implement is the compare_function, which takes in two arguments of type "const void", which can be cast to appropriate data structure, and then return one of these three values:

  • negative, if a should be before b
  • 0, if a equal to b
  • positive, if a should be after b

1. Comparing a list of integers:

simply cast a and b to integers if x < y,x-y is negative, x == y, x-y = 0, x > y, x-y is positive x-y is a shortcut way to do it :) reverse *x - *y to *y - *x for sorting in decreasing/reverse order

int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;
}

2. Comparing a list of strings:

For comparing string, you need strcmp function inside <string.h> lib. strcmp will by default return -ve,0,ve appropriately... to sort in reverse order, just reverse the sign returned by strcmp

#include <string.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}

3. Comparing floating point numbers:

int compare_function(const void *a,const void *b) {
double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;
}

4. Comparing records based on a key:

Sometimes you need to sort a more complex stuffs, such as record. Here is the simplest way to do it using qsort library.

typedef struct {
int key;
double value;
} the_record;

int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
}

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I recently encounter this issue when I copy the source code from another machine.

-> Delete the .vs folder (it is hidden folder, so make sure you have enable view hidden folder option)
-> open visual studio and build your project. Visual studio will create new .vs folder as per current system configuration

How to get the first word in the string

Use this regex

^\w+

\w+ matches 1 to many characters.

\w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don't want the space

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Use RSA private key to generate public key?

People looking for SSH public key...

If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently

$ ssh-keygen -y -f mykey.pem > mykey.pub

This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys and you'll be good to go


docs from SSH-KEYGEN(1)

ssh-keygen -y [-f input_keyfile]  

-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.

How to get the error message from the error code returned by GetLastError()?

MSDN has some sample code that demonstrates how to use FormatMessage() and GetLastError() together: Retrieving the Last-Error Code

How can I read the contents of an URL with Python?

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
    url:
    data = url.read()

print data

# When the server does not know where the request is coming from.
# Works on python 3.

import urllib.request

user_agent = \
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}

request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

How to extract a string between two delimiters

If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:

\[(.*?)\] this is your pattern. And in each group(1) will get you your string.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
    m.group(1); //is your string. do what you want
}

Can Flask have optional URL parameters?

Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class UserAPI(Resource):
    def show(userId, username=None):
    pass

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')

if __name__ == '__main__':
    app.run()

The add_resource method allows pass multiples URLs. Each one will be routed to your Resource.

Initializing a list to a known number of elements in Python

You should consider using a dict type instead of pre-initialized list. The cost of a dictionary look-up is small and comparable to the cost of accessing arbitrary list element.

And when using a mapping you can write:

aDict = {}
aDict[100] = fetchElement()
putElement(fetchElement(), fetchPosition(), aDict)

And the putElement function can store item at any given position. And if you need to check if your collection contains element at given index it is more Pythonic to write:

if anIndex in aDict:
    print "cool!"

Than:

if not myList[anIndex] is None:
    print "cool!"

Since the latter assumes that no real element in your collection can be None. And if that happens - your code misbehaves.

And if you desperately need performance and that's why you try to pre-initialize your variables, and write the fastest code possible - change your language. The fastest code can't be written in Python. You should try C instead and implement wrappers to call your pre-initialized and pre-compiled code from Python.

How to print an exception in Python 3?

Although if you want a code that is compatible with both python2 and python3 you can use this:

import logging
try:
    1/0
except Exception as e:
    if hasattr(e, 'message'):
        logging.warning('python2')
        logging.error(e.message)
    else:
        logging.warning('python3')
        logging.error(e)

Show space, tab, CRLF characters in editor of Visual Studio

The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.

Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

git: can't push (unpacker error) related to permission issues

This problem can also occur after Ubuntu upgrades that require a reboot.

If the file /var/run/reboot-required exists, do or schedule a restart.

Default property value in React component using TypeScript

With Typescript 3.0 there is a new solution to this issue:

export interface Props {
    name: string;
}

export class Greet extends React.Component<Props> {
    render() {
        const { name } = this.props;
        return <div>Hello ${name.toUpperCase()}!</div>;
    }
    static defaultProps = { name: "world"};
}

// Type-checks! No type assertions needed!
let el = <Greet />

Note that for this to work you need a newer version of @types/react than 16.4.6. It works with 16.4.11.

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Server cannot set status after HTTP headers have been sent IIS7.5

I apologize, but I'm adding my 2 cents to the thread just in case anyone has the same problem.

  • I used Forms Authentication in my MVC app
  • But some controller-actions were "anonymous" i.e. allowed to non-authenticated users
  • Sometimes in those actions I would still want users to be redirected to the login form under some condition
  • to do that - I have this in my action method: return new HttpStatusCodeResult(401) - and ASP.NET is super nice to detect this, and it redirects the user to the login page! Magic, right? It even has the proper ReturnUrl parameter etc.

But you see where I'm getting here? I return 401. And ASP.NET redirects the user. Which is essentially returns 302. One status code is replaced with another.

And some IIS servers (just some!) throw this exception. Some don't. - I don't have it on my test serevr, only on my production server (ain't it always the case right o_O)

I know my answer is essentially repeating what's already said here, but sometimes it's just hard to figure out where this overwriting happens exactly.

get current date with 'yyyy-MM-dd' format in Angular 4

Here is the example:

function MethodName($scope)
{
    $scope.date = new Date();
}

You can change the format in view here we have a code

<div ng-app ng-controller="MethodName">
    My current date is {{date | date:'yyyy-MM-dd'}} . 
</div>

I hope it helps.

HTTP GET with request body

What you're trying to achieve has been done for a long time with a much more common method, and one that doesn't rely on using a payload with GET.

You can simply build your specific search mediatype, or if you want to be more RESTful, use something like OpenSearch, and POST the request to the URI the server instructed, say /search. The server can then generate the search result or build the final URI and redirect using a 303.

This has the advantage of following the traditional PRG method, helps cache intermediaries cache the results, etc.

That said, URIs are encoded anyway for anything that is not ASCII, and so are application/x-www-form-urlencoded and multipart/form-data. I'd recommend using this rather than creating yet another custom json format if your intention is to support ReSTful scenarios.

$("#form1").validate is not a function

If you had a link I could look to see what the issue is but here are a couple questions and things to check:

  • Is the ID for your form named "form" in the HTML?
  • Check to see if messages are required, maybe there is some imbalance in parameters
  • You should also add the 'type="text/javascript"' attributes where you are getting jQuery from Google

Also, if you're going to use the Google CDN for getting jQuery you may as well use Microsoft's CDN for getting your validation file. Any of these URLs will work:

AndroidStudio gradle proxy

In Android Studio -> Preferences -> Gradle, pass the proxy details as VM options.

Gradle VM Options -Dhttp.proxyHost=www.somehost.org -Dhttp.proxyPort=8080 etc.

*In 0.8.6 Beta Gradle is under File->Settings (Ctrl+Alt+S, on Windows and Linux)

./configure : /bin/sh^M : bad interpreter

If you could not found run the command,

CentOS:

# yum install dos2unix*

# dos2unix filename.sh
dos2unix: converting file filename.sh to Unix format ...

Ubuntu / Debian:

# apt-get install dos2unix

Does overflow:hidden applied to <body> work on iPhone Safari?

Simply change body height < 300px (height of mobile viewport on landspace is around 300px to 500px)

JS

$( '.offcanvas-toggle' ).on( 'click', function() {
    $( 'body' ).toggleClass( 'offcanvas-expanded' );
});

CSS

.offcanvas-expended { /* this is class added to body on click */
    height: 200px;
}
.offcanvas {
    height: 100%;
}

C# Sort and OrderBy comparison

No, they aren't the same algorithm. For starters, the LINQ OrderBy is documented as stable (i.e. if two items have the same Name, they'll appear in their original order).

It also depends on whether you buffer the query vs iterate it several times (LINQ-to-Objects, unless you buffer the result, will re-order per foreach).

For the OrderBy query, I would also be tempted to use:

OrderBy(n => n.Name, StringComparer.{yourchoice}IgnoreCase);

(for {yourchoice} one of CurrentCulture, Ordinal or InvariantCulture).

List<T>.Sort

This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

Enumerable.OrderBy

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key. sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

Calling an API from SQL Server stored procedure

I think it would be easier using this CLR Stored procedure SQL-APIConsumer:

 exec [dbo].[APICaller_POST]
     @URL = 'http://localhost:5000/api/auth/login'
    ,@BodyJson = '{"Username":"gdiaz","Password":"password"}'

It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.

enter image description here

enter image description here

How to get text from EditText?

String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);

Can a class member function template be virtual?

No, template member functions cannot be virtual.

What is the HTML tabindex attribute?

tabindex is a global attribute responsible for two things:

  1. it sets the order of "focusable" elements and
  2. it makes elements "focusable".

In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0" on all such elements:

<div tabindex="0"></div>

Also, if you don't want it to be focusable via the tab key then use tabindex="-1". For example, the below link will not be focused while using tab keys to traverse.

<a href="#" tabindex="-1">Tab key cannot reach here!</a>

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Finding height in Binary Search Tree

public int getHeight(Node node)
{
    if(node == null)
        return 0;

    int left_val = getHeight(node.left);
    int right_val = getHeight(node.right);
    if(left_val > right_val)
        return left_val+1;
    else
        return right_val+1;
}

ReCaptcha API v2 Styling

I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform, filter is also applied to iframe elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:

.g-recaptcha {
    filter: invert(1) hue-rotate(180deg);
}

The hue-rotate(180deg) makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()'ed to black and vice versa.

Didn't see this in any answer or comment so decided to share even if this is an old thread.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

How to get an input text value in JavaScript

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

HTML5 Video tag not working in Safari , iPhone and iPad

Working around for few days into the same problem (and after check "playsinline" and "autoplay" and "muted" ok, "mime-types" and "range" in server ok, etc). The solution for all browsers was:

<video controls autoplay loop muted playsinline>
    <source src="https://example.com/my_video.mov" type="video/mp4">
</video>

Yes: convert video to .MOV and type="video/mp4" in the same tag. Working!

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

You should use:

dir.Delete(true);

for recursively deleting the contents of that folder too. See MSDN DirectoryInfo.Delete() overloads.

How to put text in the upper right, or lower right corner of a "box" using css

You need to put "here" into a <div> or <span> with style="float: right".

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

Getting "cannot find Symbol" in Java project in Intellij

For me was a problem with Lombok, because it requires Annotation Processing to be enabled. You can find this checkbox on Settings > Build > Compiler > Annotation Processors

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

IIS_IUSRS and IUSR permissions in IIS8

IUSR is part of IIS_IUSER group.so i guess you can remove the permissions for IUSR without worrying. Further Reading

However, a problem arose over time as more and more Windows system services started to run as NETWORKSERVICE. This is because services running as NETWORKSERVICE can tamper with other services that run under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code), it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities. The Windows operating system provides a feature called "Virtual Accounts" that allows IIS to create unique identities for each of its Application Pools. DefaultAppPool is the by default pool that is assigned to all Application Pool you create.

To make it more secure you can change the IIS DefaultAppPool Identity to ApplicationPoolIdentity.

Regarding permission, Create and Delete summarizes all the rights that can be given. So whatever you have assigned to the IIS_USERS group is that they will require. Nothing more, nothing less.

hope this helps.

Oracle - How to create a materialized view with FAST REFRESH and JOINS

You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.

Bubble Sort Homework

To explain why your script isn't working right now, I'll rename the variable unsorted to sorted.

At first, your list isn't yet sorted. Of course, we set sorted to False.

As soon as we start the while loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set sorted back to False. sorted will remain True only if there were no elements in the wrong order.

sorted = False  # We haven't started sorting yet

while not sorted:
    sorted = True  # Assume the list is now sorted
    for element in range(0, length):
        if badList[element] > badList[element + 1]:
            sorted = False  # We found two elements in the wrong order
            hold = badList[element + 1]
            badList[element + 1] = badList[element]
            badList[element] = hold
    # We went through the whole list. At this point, if there were no elements
    # in the wrong order, sorted is still True. Otherwise, it's false, and the
    # while loop executes again.

There are also minor little issues that would help the code be more efficient or readable.

  • In the for loop, you use the variable element. Technically, element is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like i for "index".

    for i in range(0, length):
    
  • The range command can also take just one argument (named stop). In that case, you get a list of all the integers from 0 to that argument.

    for i in range(length):
    
  • The Python Style Guide recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles.

    def bubble(bad_list):
    
  • To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, (badList[i+1], badList[i]) is (3, 5)) and then gets assigned to the two variables on the left hand side ((badList[i], badList[i+1])).

    bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
    

Put it all together, and you get this:

my_list = [12, 5, 13, 8, 9, 65]

def bubble(bad_list):
    length = len(bad_list) - 1
    sorted = False

    while not sorted:
        sorted = True
        for i in range(length):
            if bad_list[i] > bad_list[i+1]:
                sorted = False
                bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]

bubble(my_list)
print my_list

(I removed your print statement too, by the way.)

Replace Div Content onclick

EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


Here is an example of how it could work:

Working jsFiddle Demo

HTML:

<div id="someDiv">
    Once upon a midnight dreary
    <br>While I pondered weak and weary
    <br>Over many a quaint and curious
    <br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />

<input type="hidden" id="vault" />

javascript/jQuery:

//Declare persistent vars outside function
var savText, newText, myState = 0;

$('#mybutt').click(function(){
    if (myState==0){
        savText = $('#someDiv').html(); //save poem data from DIV
        newText = $('#replacementtext').val(); //save data from input field
        $('#replacementtext').val(''); //clear input field
        $('#someDiv').html( newText ); //replace poem with insert field data
        myState = 1; //remember swap has been done once
    } else {
        $('#someDiv').html(savText);
        $('#replacementtext').val(newText); //replace contents
        myState = 0;
    }
});

How to create a DataTable in C# and how to add rows?

// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I would imagine that the caching DNS servers you're using aren't behaving properly (or the DNS server for the domain you're resolving isn't working properly). You can try to fix the former possibility.

Do you have at least 2 name servers registered on your network adapter? You could always swap your computer over to use a different caching DNS server to rule this out. Try Google's:

8.8.8.8
8.8.4.4

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

It's possible that the modules are installed, but your PHP.ini still points to an old directory.

Check the contents of /usr/lib/php/extensions. In mine, there were two directories: no-debug-non-zts-20060613 and no-debug-non-zts-20060613. Around line 428 of your php.ini, change:

extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613"

to

extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20090626"

Then restart apache. This should resolve the issue.

How to pass a PHP variable using the URL

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

What is "Advanced" SQL?

Some "Advanced" features

  • recursive queries
  • windowing/ranking functions
  • pivot and unpivot
  • performance tuning

Add a linebreak in an HTML text area

In a text area, as in the form input, then just a normal line break will work:

<textarea>
This is a text area
line breaks are automatic
</textarea>

If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.

However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:

<p>
  This is some text
</p>
<p>
  This is some more
</p>

Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Is there any way to kill a Thread?

Just to build up on @SCB's idea (which was exactly what I needed) to create a KillableThread subclass with a customized function:

from threading import Thread, Event

class KillableThread(Thread):
    def __init__(self, sleep_interval=1, target=None, name=None, args=(), kwargs={}):
        super().__init__(None, target, name, args, kwargs)
        self._kill = Event()
        self._interval = sleep_interval
        print(self._target)

    def run(self):
        while True:
            # Call custom function with arguments
            self._target(*self._args)

            # If no kill signal is set, sleep for the interval,
            # If kill signal comes in while sleeping, immediately
            #  wake up and handle
            is_killed = self._kill.wait(self._interval)
            if is_killed:
                break

        print("Killing Thread")

    def kill(self):
        self._kill.set()

if __name__ == '__main__':

    def print_msg(msg):
        print(msg)

    t = KillableThread(10, print_msg, args=("hello world"))
    t.start()
    time.sleep(6)
    print("About to kill thread")
    t.kill()

Naturally, like with @SBC, the thread doesn't wait to run a new loop to stop. In this example, you would see the "Killing Thread" message printed right after the "About to kill thread" instead of waiting for 4 more seconds for the thread to complete (since we have slept for 6 seconds already).

Second argument in KillableThread constructor is your custom function (print_msg here). Args argument are the arguments that will be used when calling the function (("hello world")) here.

Rails ActiveRecord date between

there are several ways. You can use this method:

start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)

Or this:

@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

Read file line by line using ifstream in C++

This is a general solution to loading data into a C++ program, and uses the readline function. This could be modified for CSV files, but the delimiter is a space here.

int n = 5, p = 2;

int X[n][p];

ifstream myfile;

myfile.open("data.txt");

string line;
string temp = "";
int a = 0; // row index 

while (getline(myfile, line)) { //while there is a line
     int b = 0; // column index
     for (int i = 0; i < line.size(); i++) { // for each character in rowstring
          if (!isblank(line[i])) { // if it is not blank, do this
              string d(1, line[i]); // convert character to string
              temp.append(d); // append the two strings
        } else {
              X[a][b] = stod(temp);  // convert string to double
              temp = ""; // reset the capture
              b++; // increment b cause we have a new number
        }
    }

  X[a][b] = stod(temp);
  temp = "";
  a++; // onto next row
}

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Cookies on localhost with explicit domain

I was playing around a bit.

Set-Cookie: _xsrf=2|f1313120|17df429d33515874d3e571d1c5ee2677|1485812120; Domain=localhost; Path=/

works in Firefox and Chrome as of today. However, I did not find a way to make it work with curl. I tried Host-Header and --resolve, no luck, any help appreciated.

However, it works in curl, if I set it to

Set-Cookie: _xsrf=2|f1313120|17df429d33515874d3e571d1c5ee2677|1485812120; Domain=127.0.0.1; Path=/

instead. (Which does not work with Firefox.)

Javascript: how to validate dates in format MM-DD-YYYY?

Simple way to solve

var day = document.getElementById("DayTextBox").value;

var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;

return regExp.test(day);

How to amend older Git commit?

In case the OP wants to squash the 2 commits specified into 1, here is an alternate way to do it without rebasing

git checkout HEAD^               # go to the first commit you want squashed
git reset --soft HEAD^           # go to the second one but keep the tree and index the same
git commit --amend -C HEAD@{1}   # use the message from first commit (omit this to change)
git checkout HEAD@{3} -- .       # get the tree from the commit you did not want to touch
git add -A                       # add everything
git commit -C HEAD@{3}           # commit again using the message from that commit

The @{N) syntax is handy to know as it will allow you to reference the history of where your references were. In this case it's HEAD which represents your current commit.

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost