Programs & Examples On #Interface orientation

How to use "/" (directory separator) in both Linux and Windows in Python?

You can use "os.sep "

 import os
 pathfile=os.path.dirname(templateFile)
 directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
 rootTree.write(directory)

How do I count cells that are between two numbers in Excel?

Example-

For cells containing the values between 21-31, the formula is:

=COUNTIF(M$7:M$83,">21")-COUNTIF(M$7:M$83,">31")

SQL Server function to return minimum date (January 1, 1753)

Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

Limit on the WHERE col IN (...) condition

You did not specify the database engine in question; in Oracle, an option is to use tuples like this:

SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)

This ugly hack only works in Oracle SQL, see https://asktom.oracle.com/pls/asktom/asktom.search?tag=limit-and-conversion-very-long-in-list-where-x-in#9538075800346844400

However, a much better option is to use stored procedures and pass the values as an array.

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

Class type check in TypeScript

TypeScript have a way of validating the type of a variable in runtime. You can add a validating function that returns a type predicate. So you can call this function inside an if statement, and be sure that all the code inside that block is safe to use as the type you think it is.

Example from the TypeScript docs:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

See more at: https://www.typescriptlang.org/docs/handbook/advanced-types.html

C++ - how to find the length of an integer

Being a computer nerd and not a maths nerd I'd do:

char buffer[64];
int len = sprintf(buffer, "%d", theNum);

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

Create two threads, one display odd & other even numbers

Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.

public class ThreadingOddEvenNumbers {

    void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(57);
        Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter");
        Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter");
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}

class MyRunner implements Runnable {
    private Printer p;
    private boolean evenProperty;

    public MyRunner(Printer p, boolean evenNess) {
        this.p = p;
        evenProperty = evenNess;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            System.out.println(this.getClass().getName() + " "
                    + ex.getMessage());
        }
    }


    public void print() throws InterruptedException {
        while (!p.isJobComplete()) {
            synchronized (p) {
                if (evenProperty)
                    while (p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
                else
                    while (!p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
            }

            synchronized (p) {
                if (evenProperty)
                    p.printEven(Thread.currentThread().getName());
                else
                    p.printOdd(Thread.currentThread().getName());
                p.notifyAll();
                System.out.println("notify called: by: "
                        + Thread.currentThread().getName());
            }
        }
    }
}

class Printer {
    private volatile boolean evenPrinted;
    private volatile boolean jobComplete;
    private int limit;
    private int counter;

    public Printer(int lim) {
        limit = lim;
        counter = 1;
        evenPrinted = true;
        jobComplete = false;
    }

    public void printEven(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = true;
    }

    public void printOdd(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = false;
    }

    private void incrCounter() {
        counter++;
        if (counter >= limit)
            jobComplete = true;
    }

    public int getLimit() {
        return limit;
    }

    public boolean isEvenPrinted() {
        return evenPrinted;
    }

    public boolean isJobComplete() {
        return jobComplete;
    }
}

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

input type=file show only button

You could label an image so when you click on it the click event of the button will be triggered. You can simply make the normal button invisible:

<form>
    <label for="fileButton"><img src="YourSource"></label>    <!--You don't have to put an image here, it can be anything you like-->
    <input type="file" id="fileButton" style="display:none;"/>
</form>

It worked for me on all browsers, and is very easy to use.

bootstrap 3 - how do I place the brand in the center of the navbar?

Another option is to use nav-justified..

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav nav-justified">
      <li><a href="#" class="navbar-brand">Brand</a></li>
    </ul>
  </div>
</nav>

CSS

.navbar-brand {
    float:none;
}

Bootply

Alternate example

How to trim a file extension from a String in JavaScript?

This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.

It works for:

  • files without an extension: "myletter"
  • files with '.' in the name: "my.letter.txt"
  • unknown length of file extension: "my.letter.html"

Here's the code:

var filename = "my.letter.txt" // some filename

var substrings = filename.split('.'); // split the string at '.'
if (substrings.length == 1)
{
  return filename; // there was no file extension, file was something like 'myfile'
}
else
{
  var ext = substrings.pop(); // remove the last element
  var name = substrings.join(""); // rejoin the remaining elements without separator
  name = ([name, ext]).join("."); // readd the extension
  return name;
}

How does the JPA @SequenceGenerator annotation work

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

How to make Regular expression into non-greedy?

You are right that greediness is an issue:

--A--Z--A--Z--
  ^^^^^^^^^^
     A.*Z

If you want to match both A--Z, you'd have to use A.*?Z (the ? makes the * "reluctant", or lazy).

There are sometimes better ways to do this, though, e.g.

A[^Z]*+Z

This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.

In your case, the regex would be:

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

Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:

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

See also


Quick summary

*   Zero or more, greedy
*?  Zero or more, reluctant
*+  Zero or more, possessive

+   One or more, greedy
+?  One or more, reluctant
++  One or more, possessive

?   Zero or one, greedy
??  Zero or one, reluctant
?+  Zero or one, possessive

Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m} constructs.

Examples in Java:

System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!"));  // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"

System.out.println("xxxxxx".replaceAll("x{3,5}", "Y"));  // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"

How to do an array of hashmaps?

The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)

NullInjectorError: No provider for AngularFirestore

You should add providers: [AngularFirestore] in app.module.ts.

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],
  declarations: [ AppComponent ],
  providers: [AngularFirestore],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
    int x = (int)event.getX();
    int y = (int)event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }

    return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.

How to change the default encoding to UTF-8 for Apache?

Just a hint if you have long filenames in utf-8: by default they will be shortened to 20 bytes, so it may happen that the last character might be "cut in half" and therefore unrecognized properly. Then you may want to set the following:

IndexOptions Charset=UTF-8 NameWidth=*

NameWidth setting will prevent shortening your file names, making them properly displayed and readable.

As other users already mentioned, this should be added either in httpd.conf or apache2.conf (if you do have admin rights) or in .htaccess (if you don't).

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

How can I increase the size of a bootstrap button?

Just simply add to the class of the bootstrap code.

_x000D_
_x000D_
.login
{
width: 20%;
margin-top: 39.5%;
margin-left: 35%;
}
_x000D_
<button type="button" class="btn btn-outline-dark btn-lg login">Login</button> 
_x000D_
_x000D_
_x000D_

How to declare empty list and then add string in scala?

Scala lists are immutable by default. You cannot "add" an element, but you can form a new list by appending the new element in front. Since it is a new list, you need to reassign the reference (so you can't use a val).

var dm  = List[String]()
var dk = List[Map[String,AnyRef]]()

.....

dm = "text" :: dm
dk = Map(1 -> "ok") :: dk

The operator :: creates the new list. You can also use the shorter syntax:

dm ::= "text" 
dk ::= Map(1 -> "ok")

NB: In scala don't use the type Object but Any, AnyRef or AnyVal.

How to open a URL in a new Tab using JavaScript or jQuery?

This is as simple as this.

window.open('_link is here_', 'name'); 

Function description:

name is a name of the window. Following names are supported:

  • _blank - URL is loaded into a new tab. This is default.
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded

MSVCP120d.dll missing

I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

download rpm packages and run the following command:

rpm -Uvh glibc-2.15-60.el6.x86_64.rpm \
glibc-common-2.15-60.el6.x86_64.rpm \
glibc-devel-2.15-60.el6.x86_64.rpm \
glibc-headers-2.15-60.el6.x86_64.rpm

APT command line interface-like yes/no input?

For Python 3, I'm using this function:

def user_prompt(question: str) -> bool:
    """ Prompt the yes/no-*question* to the user. """
    from distutils.util import strtobool

    while True:
        user_input = input(question + " [y/n]: ")
        try:
            return bool(strtobool(user_input))
        except ValueError:
            print("Please use y/n or yes/no.\n")

The strtobool() function converts a string into a bool. If the string cant be parsed it will raise a ValueError.

In Python 3 raw_input() has been renamed to input().

As Geoff said, strtobool actually returns 0 or 1, therefore the result has to be cast to bool.


This is the implementation of strtobool, if you want special words to be recognized as true, you can copy the code and add your own cases.

def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).
    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (val,))

How to create a new component in Angular 4 using CLI

In Angular4 this will work the same. If you get an error I think your problem is somewhere else.

In command prompt type

ng generate component YOURCOMPONENTNAME

There are even shorthands for this: the commands generate can be used as g and component as c:

ng g c YOURCOMPONENTNAME

you can use ng --help, ng g --help or ng g c --help for the docs.

Ofcourse rename YOURCOMPONENTNAME to the name you would like to use.

Docs: angular-cli will add reference to components, directives and pipes automatically in the app.module.ts.

Update: This still functions in Angular version 8.

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

Deploy the app as exploded (project.war folder), add in your web.xml:

<web-app>
    <context-param>
        <param-name>org.jboss.weld.development</param-name>
        <param-value>true</param-value>
    </context-param>

Update the web.xml time every-time you deploy (append blank line):

set PRJ_HOME=C:\Temp2\MyProject\src\main\webapp
set PRJ_CLSS_HOME=%PRJ_HOME%\WEB-INF\classes\com\myProject

set JBOSS_HOME= C:\Java\jboss-4.2.3.GA-jdk6\server\default\deploy\MyProject.war
set JBOSS_CLSS_HOME= %JBOSS_HOME%\WEB-INF\classes\com\myProject

copy %PRJ_CLSS_HOME%\frontend\actions\profile\ProfileAction.class %JBOSS_CLSS_HOME%\frontend\actions\profile\ProfileAction.class
copy %PRJ_CLSS_HOME%\frontend\actions\profile\AjaxAction.class %JBOSS_CLSS_HOME%\frontend\actions\profile\AjaxAction.class

ECHO.>>%JBOSS_HOME%\WEB-INF\web.xml

Android camera android.hardware.Camera deprecated

Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight

   public class MainActivity extends AppCompatActivity {

     Button button;

     Boolean light=true;

     CameraDevice cameraDevice;

     private CameraManager cameraManager;

     private CameraCharacteristics cameraCharacteristics;

     String cameraId;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        cameraManager = (CameraManager) 
        getSystemService(Context.CAMERA_SERVICE);
        try {
          cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    try {

                        cameraManager.setTorchMode(cameraId,true);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                    light=false;}
                    else {

                    try {

                      cameraManager.setTorchMode(cameraId,false);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }


                    light=true;
                    }


            }
        });
    }
}

Open fancybox from function

You do not have to trigger a click event, you can do it with fancybox type as ajax.  

$.fancybox.open({
      href: "http://........",
      type: 'ajax'
});

Java RegEx meta character (.) and ordinary dot?

Here is code you can directly copy paste :

String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
   system.out.println(imageNameArray[i]);
}

And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.

String imageName = "picture1  . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
    for(int i =0; i< imageNameArray.length ; i++)
    {
       system.out.println(imageNameArray[i]);
    }

Here, \\s* is there to consider the spaces and give you only required splitted strings.

Mercurial undo last commit

Its workaround.

If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.

Log all queries in mysql

Quick way to enable MySQL General Query Log without restarting.

mysql> SET GLOBAL general_log = 'ON';
mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';

I have installed mysql through homebrew, mysql version : mysql Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper

How to disable registration new users in Laravel

In Laravel 5.5 is very simple, if you are using CRUD route system.

Go to app/http/controllers/RegisterController there is namespace: Illuminate\Foundation\Auth\RegistersUser

You need to go to the RegistersUser: Illuminate\Foundation\Auth\RegistersUser

There is the method call showRegistrationForm change this: return view('auth.login'); for this: return redirect()->route('auth.login'); and remove from you blade page route call register. It may look like that:

 <li role="presentation">
     <a class="nav-link" href="{{ route('register') }}">Register</a>
 </li> 

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

Is there a JavaScript function that can pad a string to get to a determined length?

  1. Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end!
  2. Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string.
  3. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

_x000D_
_x000D_
if (!String.prototype.lpad) {_x000D_
    String.prototype.lpad = function(pad, len) {_x000D_
        while (pad.length < len) {_x000D_
            pad += pad;_x000D_
        }_x000D_
        return pad.substr(0, len-this.length) + this;_x000D_
    }_x000D_
}_x000D_
_x000D_
if (!String.prototype.rpad) {_x000D_
    String.prototype.rpad = function(pad, len) {_x000D_
        while (pad.length < len) {_x000D_
            pad += pad;_x000D_
        }_x000D_
        return this + pad.substr(0, len-this.length);_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

How do I copy a version of a single file from one git branch to another?

Run this from the branch where you want the file to end up:

git checkout otherbranch myfile.txt

General formulas:

git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>

Some notes (from comments):

  • Using the commit hash you can pull files from any commit
  • This works for files and directories
  • overwrites the file myfile.txt and mydir
  • Wildcards don't work, but relative paths do
  • Multiple paths can be specified

an alternative:

git show commit_id:path/to/file > path/to/file

Linking to a specific part of a web page

First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id" Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated. But instead of

> http://url.to.site/index.html#target

You would put

> http://storedomain.com/target

For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235 for my hyperlink. Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores. If you want to link to something other than your homepage you would put

> http://mystore-classifier.com/pagename/#BlockID

I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

how to check for null with a ng-if values in a view with angularjs?

You should check for !test, here is a fiddle showing that.

<span ng-if="!test">null</span>

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

Split / Explode a column of dictionaries into separate columns with pandas

One line solution is following:

>>> df = pd.concat([df['Station ID'], df['Pollutants'].apply(pd.Series)], axis=1)
>>> print(df)
   Station ID    a    b   c
0        8809   46    3  12
1        8810   36    5   8
2        8811  NaN    2   7
3        8812  NaN  NaN  11
4        8813   82  NaN  15

Set adb vendor keys

Sometimes you just need to recreate new device

Unable to find a @SpringBootConfiguration when doing a JpaTest

It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.

How to reload a page using Angularjs?

You need $route defined in your module and change the JS to this.

$scope.backLinkClick = function () {
  window.location.reload(); 
};

that works fine for me.

Get Environment Variable from Docker Container

The downside of using docker exec is that it requires a running container, so docker inspect -f might be handy if you're unsure a container is running.

Example #1. Output a list of space-separated environment variables in the specified container:

docker inspect -f \
   '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name

the output will look like this:

ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3

Example #2. Output each env var on new line and grep the needed items, for example, the mysql container's settings could be retrieved like this:

docker inspect -f \
    '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \
    container_name | grep MYSQL_

will output:

MYSQL_PASSWORD=secret
MYSQL_ROOT_PASSWORD=supersecret
MYSQL_USER=demo
MYSQL_DATABASE=demodb
MYSQL_MAJOR=5.5
MYSQL_VERSION=5.5.52

Example #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts:

docker inspect -f \
   '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \
   container_name | grep MYSQL

will output:

export MYSQL_PASSWORD=secret
export MYSQL_ROOT_PASSWORD=supersecret
export MYSQL_USER=demo
export MYSQL_DATABASE=demodb
export MYSQL_MAJOR=5.5
export MYSQL_VERSION=5.5.52

If you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format.

Open a facebook link by native Facebook app on iOS

Here are some schemes the Facebook app uses, there are a ton more on the source link:

Example

NSURL *url = [NSURL URLWithString:@"fb://profile/<id>"];
[[UIApplication sharedApplication] openURL:url];

Schemes

fb://profile – Open Facebook app to the user’s profile

fb://friends – Open Facebook app to the friends list

fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)

fb://feed – Open Facebook app to the News Feed

fb://events – Open Facebook app to the Events page

fb://requests – Open Facebook app to the Requests list

fb://notes – Open Facebook app to the Notes page

fb://albums – Open Facebook app to Photo Albums list

If before opening this url you want to check wether the user fas the facebook app you can do the following (as explained in another answer below):

if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
    [[UIApplication sharedApplication] openURL:nsurl];
}
else {
    //Open the url as usual
}

Source

http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

Error in Python script "Expected 2D array, got 1D array instead:"?

With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.

if type(X) is Series:
    X = X.to_frame()

Bash script prints "Command Not Found" on empty lines

I ran into this today, absentmindedly copying the dollar command prompt $ (ahead of a command string) into the script.

What does "The APR based Apache Tomcat Native library was not found" mean?

Had this problem as well. If you do have the libraries, but still have this error, it may be a configuration error. Your server.xml may be missing the following line:

 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

(Alternatively, it may be commented out). This <Listener>, like other listeners is a child of the top-level <Server>.

Without the <Listener> line, there's no attempt to load the APR library, so LD_LIBRARY_PATH and -Djava.library.path= settings are ignored.

oracle SQL how to remove time from date

When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:

select 
    p1.PA_VALUE as StartDate,
    p2.PA_VALUE as EndDate
from WP_Work p 
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
LEFT JOIN PARAMETER p2 on p2.WP_ID=p.WP_ID AND p2.NAME = 'Date_To'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')

Java: Find .txt files in specified folder

I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.

The only plus this code gives is that it can iterate through sub-directories as well.

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

Method is as follows:

List <File> exploreThis(String dirPath){

    File topDir = new File(dirPath);

    List<File> directories = new ArrayList<>();
    directories.add(topDir);

    List<File> textFiles = new ArrayList<>();

    List<String> filterWildcards = new ArrayList<>();
    filterWildcards.add("*.txt");
    filterWildcards.add("*.doc");

    FileFilter typeFilter = new WildcardFileFilter(filterWildcards);

    while (directories.isEmpty() == false)
    {
        List<File> subDirectories = new ArrayList();

        for(File f : directories)
        {
            subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
            textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
        }

        directories.clear();
        directories.addAll(subDirectories);
    }

    return textFiles;
}

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.

Java properties UTF-8 encoding in Eclipse

This seems to work only for some characters ... including special characters for German, Portuguese, French. However, I ran into trouble with Russian, Hindi and Mandarin characters. These are not converted to Properties format 'native2ascii', instead get saved with ?? ?? ??
The only way I could get my app to display these characters correctly is by putting them in the properties file translated to UTF-8 format - as \u0915 instead of ?, or \u044F instead of ?. Any advice?

How to populate/instantiate a C# array with a single value?

There is no way to set all elements in an array as a single operation, UNLESS, that value is the element types default value.

Eg, if it is an array of integers you can set them all to zero with a single operation, like so: Array.Clear(...)

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

Tomcat: How to find out running tomcat version

run on terminal of the Unix server

w3m http://localhost:8080/

to quit press q and next y

How to read data when some numbers contain commas as thousand separator?

A very convenient way is readr::read_delim-family. Taking the example from here: Importing csv with multiple separators into R you can do it as follows:

txt <- 'OBJECTID,District_N,ZONE_CODE,COUNT,AREA,SUM
1,Bagamoyo,1,"136,227","8,514,187,500.000000000000000","352,678.813105723350000"
2,Bariadi,2,"88,350","5,521,875,000.000000000000000","526,307.288878142830000"
3,Chunya,3,"483,059","30,191,187,500.000000000000000","352,444.699742995200000"'

require(readr)
read_csv(txt) # = read_delim(txt, delim = ",")

Which results in the expected result:

# A tibble: 3 × 6
  OBJECTID District_N ZONE_CODE  COUNT        AREA      SUM
     <int>      <chr>     <int>  <dbl>       <dbl>    <dbl>
1        1   Bagamoyo         1 136227  8514187500 352678.8
2        2    Bariadi         2  88350  5521875000 526307.3
3        3     Chunya         3 483059 30191187500 352444.7

How do I delete an exported environment variable?

Because the original question doesn't mention how the variable was set, and because I got to this page looking for this specific answer, I'm adding the following:

In C shell (csh/tcsh) there are two ways to set an environment variable:

  1. set x = "something"
  2. setenv x "something"

The difference in the behaviour is that variables set with setenv command are automatically exported to subshell while variable set with set aren't.

To unset a variable set with set, use

unset x

To unset a variable set with setenv, use

unsetenv x

Note: in all the above, I assume that the variable name is 'x'.

credits:

https://www.cyberciti.biz/faq/unix-linux-difference-between-set-and-setenv-c-shell-variable/ https://www.oreilly.com/library/view/solaristm-7-reference/0130200484/0130200484_ch18lev1sec24.html

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

Display a tooltip over a button using Windows Forms

The .NET framework provides a ToolTip class. Add one of those to your form and then on the MouseHover event for each item you would like a tooltip for, do something like the following:

private void checkBox1_MouseHover(object sender, EventArgs e)
{
    toolTip1.Show("text", checkBox1);
}

Converting XDocument to XmlDocument and vice versa

If you need a Win 10 UWP compatible variant:

using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new DomXmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.LoadXml(xmlReader.ReadOuterXml());
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    xmlDocument.WriteContentTo(w);
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }

        public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    w.WriteRaw(xmlDocument.GetXml());
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }
    }

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.

How do I install Python packages on Windows?

As mentioned by Blauhirn after 2.7 pip is preinstalled. If it is not working for you it might need to be added to path.

However if you run Windows 10 you no longer have to open a terminal to install a module. The same goes for opening Python as well.

You can type directly into the search menu pip install mechanize, select command and it will install:

enter image description here

If anything goes wrong however it may close before you can read the error but still it's a useful shortcut.

List<Map<String, String>> vs List<? extends Map<String, String>>

As you mentioned, there could be two below versions of defining a List:

  1. List<? extends Map<String, String>>
  2. List<?>

2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>. Your consumer method might break.

In order to ensure that List can hold objects of a given type, Java generics introduced ? extends. So in #1, the List can hold any object which is derived from Map<String, String> type. Adding any other type of data would throw an exception.

Connection to SQL Server Works Sometimes

It turned out that TCP/IP was enabled for the IPv4 address, but not for the IPv6 address, of THESERVER.

Apparently some connection attempts ended up using IPv4 and others used IPv6.

Enabling TCP/IP for both IP versions resolved the issue.

The fact that SSMS worked turned out to be coincidental (the first few attempts presumably used IPv4). Some later attempts to connect through SSMS resulted in the same error message.

To enable TCP/IP for additional IP addresses:

  • Start Sql Server Configuration Manager
  • Open the node SQL Server Network Configuration
  • Left-click Protocols for MYSQLINSTANCE
  • In the right-hand pane, right-click TCP/IP
  • Click Properties
  • Select the IP Addresses tab
  • For each listed IP address, ensure Active and Enabled are both Yes.

How to write super-fast file-streaming code in C#?

(For future reference.)

Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).

Memory Mapped files are supported in managed code in .NET 4.0.

But as noted, you need to profile, and expect to switch to native code for maximum performance.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Type

netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789

perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.

http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/

CSS horizontal centering of a fixed div?

Here's a flexbox solution when using a full screen wrapper div. justify-content centers it's child div horizontally and align-items centers it vertically.

<div class="full-screen-wrapper">
    <div class="center"> //... content</div>
</div>

.full-screen-wrapper { 
  position: fixed;
  display: flex;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  top: 0;
  align-items: center;
}

.center {
  // your styles
}

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

If you have desired permissions saved to string then do

s = '660'
os.chmod(file_path, int(s, base=8))

Create Map in Java

There is even a better way to create a Map along with initialization:

Map<String, String> rightHereMap = new HashMap<String, String>()
{
    {
        put("key1", "value1");
        put("key2", "value2");
    }
};

For more options take a look here How can I initialise a static Map?

How can I run an EXE program from a Windows Service using C#?

You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.

However this is a class which works fine for my case :

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct SECURITY_ATTRIBUTES
    {
        public uint nLength;
        public IntPtr lpSecurityDescriptor;
        public bool bInheritHandle;
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public uint cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;

    }

    internal enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    internal enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public static class ProcessAsUser
    {

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);


        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
        private static extern bool DuplicateTokenEx(
            IntPtr hExistingToken,
            uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            Int32 ImpersonationLevel,
            Int32 dwTokenType,
            ref IntPtr phNewToken);


        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(
            IntPtr ProcessHandle,
            UInt32 DesiredAccess,
            ref IntPtr TokenHandle);

        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool CreateEnvironmentBlock(
                ref IntPtr lpEnvironment,
                IntPtr hToken,
                bool bInherit);


        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool DestroyEnvironmentBlock(
                IntPtr lpEnvironment);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(
            IntPtr hObject);

        private const short SW_SHOW = 5;
        private const uint TOKEN_QUERY = 0x0008;
        private const uint TOKEN_DUPLICATE = 0x0002;
        private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
        private const int GENERIC_ALL_ACCESS = 0x10000000;
        private const int STARTF_USESHOWWINDOW = 0x00000001;
        private const int STARTF_FORCEONFEEDBACK = 0x00000040;
        private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;


        private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
        {
            bool result = false;


            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
            saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
            saThread.nLength = (uint)Marshal.SizeOf(saThread);

            STARTUPINFO si = new STARTUPINFO();
            si.cb = (uint)Marshal.SizeOf(si);


            //if this member is NULL, the new process inherits the desktop
            //and window station of its parent process. If this member is
            //an empty string, the process does not inherit the desktop and
            //window station of its parent process; instead, the system
            //determines if a new desktop and window station need to be created.
            //If the impersonated user already has a desktop, the system uses the
            //existing desktop.

            si.lpDesktop = @"WinSta0\Default"; //Modify as needed
            si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
            si.wShowWindow = SW_SHOW;
            //Set other si properties as required.

            result = CreateProcessAsUser(
                token,
                null,
                cmdLine,
                ref saProcess,
                ref saThread,
                false,
                CREATE_UNICODE_ENVIRONMENT,
                envBlock,
                null,
                ref si,
                out pi);


            if (result == false)
            {
                int error = Marshal.GetLastWin32Error();
                string message = String.Format("CreateProcessAsUser Error: {0}", error);
                FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);

            }

            return result;
        }


        private static IntPtr GetPrimaryToken(int processId)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr primaryToken = IntPtr.Zero;
            bool retVal = false;
            Process p = null;

            try
            {
                p = Process.GetProcessById(processId);
            }

            catch (ArgumentException)
            {

                string details = String.Format("ProcessID {0} Not Available", processId);
                FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
                throw;
            }


            //Gets impersonation token
            retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
            if (retVal == true)
            {

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.nLength = (uint)Marshal.SizeOf(sa);

                //Convert the impersonation token into Primary token
                retVal = DuplicateTokenEx(
                    token,
                    TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
                    ref sa,
                    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    (int)TOKEN_TYPE.TokenPrimary,
                    ref primaryToken);

                //Close the Token that was previously opened.
                CloseHandle(token);
                if (retVal == false)
                {
                    string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

                }

            }

            else
            {

                string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }

            //We'll Close this token after it is used.
            return primaryToken;

        }

        private static IntPtr GetEnvironmentBlock(IntPtr token)
        {

            IntPtr envBlock = IntPtr.Zero;
            bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
            if (retVal == false)
            {

                //Environment Block, things like common paths to My Documents etc.
                //Will not be created if "false"
                //It should not adversley affect CreateProcessAsUser.

                string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }
            return envBlock;
        }

        public static bool Launch(string appCmdLine /*,int processId*/)
        {

            bool ret = false;

            //Either specify the processID explicitly
            //Or try to get it from a process owned by the user.
            //In this case assuming there is only one explorer.exe

            Process[] ps = Process.GetProcessesByName("explorer");
            int processId = -1;//=processId
            if (ps.Length > 0)
            {
                processId = ps[0].Id;
            }

            if (processId > 1)
            {
                IntPtr token = GetPrimaryToken(processId);

                if (token != IntPtr.Zero)
                {

                    IntPtr envBlock = GetEnvironmentBlock(token);
                    ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                    if (envBlock != IntPtr.Zero)
                        DestroyEnvironmentBlock(envBlock);

                    CloseHandle(token);
                }

            }
            return ret;
        }

    }

And to execute , simply call like this :

string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);

What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

How does the vim "write with sudo" trick work?

This also works well:

:w !sudo sh -c "cat > %"

This is inspired by the comment of @Nathan Long.

NOTICE:

" must be used instead of ' because we want % to be expanded before passing to shell.

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

Java Byte Array to String to Byte Array

What I did:

return to clients:

byte[] result = ****encrypted data****;

String str = Base64.encodeBase64String(result);

return str;

receive from clients:

 byte[] bytes = Base64.decodeBase64(str);

your data will be transferred in this format:

OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA== 

Counting Line Numbers in Eclipse

Search > File Search

Check the Regular expression box.

Use this expression:

\n[\s]*

Select whatever file types (*.java, *.xml, etc..) and working sets are appropriate for you.

What is the difference between fastcgi and fpm?

FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.

Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).

Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

center a row using Bootstrap 3

What you are doing is not working, because you apply the margin: auto to the full-width column.

Wrap it in a div and center that one. E.g:

<div class="i-am-centered">
  <div class="row">...</div>
</div>

.

.i-am-centered { margin: auto; max-width: 300px;}

http://www.bootply.com/93751

Its a cleaner solution anyway, as it is more expressive and as you usually don't want to mess with the grid.

How to use global variables in React Native?

Set up a flux container

simple example

import alt from './../../alt.js';

    class PostActions {
        constructor(){
        this.generateActions('setMessages');
        }

        setMessages(indexArray){
            this.actions.setMessages(indexArray);
        }
    }


export default alt.createActions(PostActions);

store looks like this

class PostStore{

    constructor(){

       this.messages = [];

       this.bindActions(MessageActions);
    }




    setMessages(messages){
        this.messages = messages;
    }
}

export default alt.createStore(PostStore);

Then every component that listens to the store can share this variable In your constructor is where you should grab it

constructor(props){
    super(props);

   //here is your data you get from the store, do what you want with it 
    var messageStore = MessageStore.getState();

}


    componentDidMount() {
      MessageStore.listen(this.onMessageChange.bind(this));
    }

    componentWillUnmount() {
      MessageStore.unlisten(this.onMessageChange.bind(this));
    }

    onMessageChange(state){ 
        //if the data ever changes each component listining will be notified and can do the proper processing. 
   }

This way, you can share you data across the app without every component having to communicate with each other.

php.ini & SMTP= - how do you pass username & password

These answers are outdated and depreciated. Best practice..

composer require phpmailer/phpmailer

The next on your sendmail.php file just require the following

# use namespace
use PHPMailer\PHPMailer\PHPMailer;

# require php mailer
require_once "../vendor/autoload.php";

//PHPMailer Object
$mail = new PHPMailer;

//From email address and name
$mail->From = "[email protected]";
$mail->FromName = "Full Name";

//To address and name
$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]"); //Recipient name is optional

//Address to which recipient will reply
$mail->addReplyTo("[email protected]", "Reply");

//CC and BCC
$mail->addCC("[email protected]");
$mail->addBCC("[email protected]");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send()) 
{
    echo "Mailer Error: " . $mail->ErrorInfo;
} 
else 
{
    echo "Message has been sent successfully";
}

This can be configure how ever you like..

OnclientClick and OnClick is not working at the same time?

OnClientClick seems to be very picky when used with OnClick.

I tried unsuccessfully with the following use cases:

OnClientClick="return ValidateSearch();" 
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"

But they did not work. The following worked:

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" 
  OnClick="keywordSearch_Click" 
  OnClientClick="if (!ValidateSearch()) { return false;};" />

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Possibly something has changed in recent TensorFlow builds, because for me, running

sess = tf.Session()
sess.run(tf.local_variables_initializer())

before fitting any models seems to do the trick. Most older examples and comments seem to suggest tf.global_variables_initializer().

Inverse dictionary lookup in Python

Make a reverse dictionary

reverse_dictionary = {v:k for k,v in dictionary.items()} 

If you have a lot of reverse lookups to do

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Singular matrix issue with Numpy

By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.

Each row is a linear combination of the first row.

Notice that the second row is just 8x the first row.

Likewise, the third row is 50x the first row.

There's only one independent row in your matrix.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to secure the ASP.NET_SessionId cookie?

Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.

    protected void Session_Start(Object sender, EventArgs e)
    {
        SessionStateSection sessionState = 
 (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
        string sidCookieName = sessionState.CookieName;

        if (Request.Cookies[sidCookieName] != null)
        {
            HttpCookie sidCookie = Response.Cookies[sidCookieName];
            sidCookie.Value = Session.SessionID;
            sidCookie.HttpOnly = true;
            sidCookie.Secure = true;
            sidCookie.Path = "/";
        }
    }

Right way to reverse a pandas DataFrame?

data.reindex(index=data.index[::-1])

or simply:

data.iloc[::-1]

will reverse your data frame, if you want to have a for loop which goes from down to up you may do:

for idx in reversed(data.index):
    print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])

or

for idx in reversed(data.index):
    print(idx, data.Even[idx], data.Odd[idx])

You are getting an error because reversed first calls data.__len__() which returns 6. Then it tries to call data[j - 1] for j in range(6, 0, -1), and the first call would be data[5]; but in pandas dataframe data[5] means column 5, and there is no column 5 so it will throw an exception. ( see docs )

Getting return value from stored procedure in C#

You say your SQL compiles fine, but I get: Must declare the scalar variable "@Password".

Also you are trying to return a varchar (@b) from your stored procedure, but SQL Server stored procedures can only return integers.

When you run the procedure you are going to get the error:

'Conversion failed when converting the varchar value 'x' to data type int.'

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

How to copy commits from one branch to another?

You should really have a workflow that lets you do this all by merging:

- x - x - x (v2) - x - x - x (v2.1)
           \
            x - x - x (wss)

So all you have to do is git checkout v2.1 and git merge wss. If for some reason you really can't do this, and you can't use git rebase to move your wss branch to the right place, the command to grab a single commit from somewhere and apply it elsewhere is git cherry-pick. Just check out the branch you want to apply it on, and run git cherry-pick <SHA of commit to cherry-pick>.

Some of the ways rebase might save you:

If your history looks like this:

- x - x - x (v2) - x - x - x (v2.1)
           \
            x - x - x (v2-only) - x - x - x (wss)

You could use git rebase --onto v2 v2-only wss to move wss directly onto v2:

- x - x - x (v2) - x - x - x (v2.1)
          |\
          |  x - x - x (v2-only)
           \
             x - x - x (wss)

Then you can merge! If you really, really, really can't get to the point where you can merge, you can still use rebase to effectively do several cherry-picks at once:

# wss-starting-point is the SHA1/branch immediately before the first commit to rebase
git branch wss-to-rebase wss
git rebase --onto v2.1 wss-starting-point wss-to-rebase
git checkout v2.1
git merge wss-to-rebase

Note: the reason that it takes some extra work in order to do this is that it's creating duplicate commits in your repository. This isn't really a good thing - the whole point of easy branching and merging is to be able to do everything by making commit(s) one place and merging them into wherever they're needed. Duplicate commits mean an intent never to merge those two branches (if you decide you want to later, you'll get conflicts).

How do I select the parent form based on which submit button is clicked?

I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

In Powershell what is the idiomatic way of converting a string to an int?

You can use the -as operator. If casting succeed you get back a number:

$numberAsString -as [int]

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

Get bytes from std::string in C++

Normally, encryption functions take

encrypt(const void *ptr, size_t bufferSize);

as arguments. You can pass c_str and length directly:

encrypt(strng.c_str(), strng.length());

This way, extra space is allocated or wasted.

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

What's the most appropriate HTTP status code for an "item not found" error page

Since it's a user-facing page always use 404. It's the only code people know usually.

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

You can go here to download the Java JRE.

You can go here to download the Java JDK.

After that you need to set up your environmental variables in Windows:

  1. Right-click My Computer
  2. Click Properties
  3. Go to Advanced System Settings
  4. Click on the Advanced tab
  5. Click on Environment Variables

EDIT: See screenshot for environmental variables

enter image description here

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

Can a unit test project load the target application's app.config file?

In Visual Studio 2008 I added the app.config file to the test project as an existing item and selected copy as link in order to make sure it's not duplicated. That way I only have one copy in my solution. With several test projects it comes in really handy!

Add Existing Item

Add As Link

How to install xgboost in Anaconda Python (Windows platform)?

  1. Look here https://github.com/Rafi993/xgboost/ for building xgboost on your machine. There are many different varieties of the solution above, but it seems that the version in the link above is the good one. At least that worked for me: I've tested it on Windows 7 and Windows Server 2008.

  2. Then run the following commands in cmd in order to install python bindings:
    cd python-package python setup.py install

  3. You might also need a proper mingw (google for tdm-gcc) and the latest setuptools from anaconda.

I hope it will help

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How to tell a Mockito mock object to return something different the next time it is called?

Or, even cleaner:

when(mockFoo.someMethod()).thenReturn(obj1, obj2);

How do you comment an MS-access Query?

if you are trying to add a general note to the overall object (query or table etc..)

Access 2016 go to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory "table last last updated 05/31/17"

Installing python module within code

The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

Use sys.executable to ensure that you will call the same pip associated with the current runtime.

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

How can I get the ID of an element using jQuery?

Above answers are great, but as jquery evolves.. so you can also do:

var myId = $("#test").prop("id");

PreparedStatement with Statement.RETURN_GENERATED_KEYS

String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);

preparedStatement.setXXX(1, VALUE); 
preparedStatement.setXXX(2, VALUE); 
....
preparedStatement.executeUpdate();  

ResultSet rs = preparedStatement.getGeneratedKeys();  
int key = rs.next() ? rs.getInt(1) : 0;

if(key!=0){
    System.out.println("Generated key="+key);
}

Locate the nginx.conf file my nginx is actually using

All other answers are useful but they may not help you in case nginx is not on PATH so you're getting command not found when trying to run nginx:

I have nginx 1.2.1 on Debian 7 Wheezy, the nginx executable is not on PATH, so I needed to locate it first. It was already running, so using ps aux | grep nginx I have found out that it's located on /usr/sbin/nginx, therefore I needed to run /usr/sbin/nginx -t.

If you want to use a non-default configuration file (i.e. not /etc/nginx/nginx.conf), run it with the -c parameter: /usr/sbin/nginx -c <path-to-configuration> -t.

You may also need to run it as root, otherwise nginx may not have permissions to open for example logs, so the command would fail.

Can I pass an array as arguments to a method with variable arguments in Java?

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

So you should just be able to prepend extraVar to args and call String.format(format, args).

Refused to load the script because it violates the following Content Security Policy directive

Adding the meta tag to ignore this policy was not helping us, because our webserver was injecting the Content-Security-Policy header in the response.

In our case we are using Ngnix as the web server for a Tomcat 9 Java-based application. From the web server, it is directing the browser not to allow inline scripts, so for a temporary testing we have turned off Content-Security-Policy by commenting.

How to turn it off in ngnix

  • By default, ngnix ssl.conf file will have this adding a header to the response:

    #> grep 'Content-Security' -ir /etc/nginx/global/ssl.conf add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'; script-src 'self'; img-src 'self'; style-src 'self'; base-uri 'self'; form-action 'self';";

  • If you just comment this line and restart ngnix, it should not be adding the header to the response.

If you are concerned about security or in production please do not follow this, use these steps as only for testing purpose and moving on.

How to get length of a string using strlen function

Manually:

int strlen(string s)
{
    int len = 0;

    while (s[len])
        len++;

    return len;
}

Python Script to convert Image into Byte array

with BytesIO() as output:
    from PIL import Image
    with Image.open(filename) as img:
        img.convert('RGB').save(output, 'BMP')                
    data = output.getvalue()[14:]

I just use this for add a image to clipboard in windows.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

A more un-obtrusive way (assuming you use jQuery):

HTML:

<a id="my-link" href="page.html">page link</a>

Javascript:

$('#my-link').click(function(e)
{
    e.preventDefault();
});

The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.

Python 3 Float Decimal Points/Precision

Try to understand through this below function using python3

def floating_decimals(f_val, dec):
    prc = "{:."+str(dec)+"f}" #first cast decimal as str
    print(prc) #str format output is {:.3f}
    return prc.format(f_val)


print(floating_decimals(50.54187236456456564, 3))

Output is : 50.542

Hope this helps you!

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

Had the same problem, and the blueimp guy says "maxFileSize and acceptFileTypes are only supported by the UI version" and has provided a (broken) link to incorporate the _validate and _hasError methods.

So without knowing how to incorporate those methods without messing up the script I wrote this little function. It seems to work for me.

Just add this

add: function(e, data) {
        var uploadErrors = [];
        var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('Not an accepted file type');
        }
        if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize is too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.submit();
        }
},

at the start of the .fileupload options as shown in your code here

$(document).ready(function () {
    'use strict';

    $('#fileupload').fileupload({
        add: function(e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                    uploadErrors.push('Not an accepted file type');
                }
                if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if(uploadErrors.length > 0) {
                    alert(uploadErrors.join("\n"));
                } else {
                    data.submit();
                }
        },
        dataType: 'json',
        autoUpload: false,
        // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        // maxFileSize: 5000000,
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
                .appendTo('#div_files');
            });
        },
        fail: function (e, data) {
            $.each(data.messages, function (index, error) {
                $('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
                .appendTo('#div_files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);

            $('#progress .bar').css('width', progress + '%');
        }
    });
});

You'll notice I added a filesize function in there as well because that will also only work in the UI version.

Updated to get past issue suggested by @lopsided: Added data.originalFiles[0]['type'].length and data.originalFiles[0]['size'].length in the queries to make sure they exist and are not empty first before testing for errors. If they don't exist, no error will be shown and it will only rely on your server side error testing.

Can we rely on String.isEmpty for checking null condition on a String in Java?

No, the String.isEmpty() method looks as following:

public boolean isEmpty() {
    return this.value.length == 0;
}

as you can see it checks the length of the string so you definitely have to check if the string is null before.

Error: Cannot find module 'ejs'

npm install ejs --save worked for me ! ?

On goormIDE, I had this file configuration :

  • container
    • main.js
    • package-lock.json
    • package.json
    • node_modules
    • views
      • home.ejs

In my main.js file, I also had this route

app.get("/", function(req, res){
res.render("home.ejs");
})

npm install ejs -g didn't add the corresponding dependency within the package.json. npm install ejs --save did. I executed the command line from the container directory. Manually it could have been added into the package.json with : **

"dependencies": {
    "ejs": "^3.0.2",}

**

addEventListener vs onclick

Using inline handlers is incompatible with Content Security Policy so the addEventListener approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.

Reset ID autoincrement ? phpmyadmin

I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.

Remove all subviews?

Get all the subviews from your root controller and send each a removeFromSuperview:

NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}

How to test abstract class in Java with JUnit?

Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.

How to style a JSON block in Github Wiki?

Some color-syntaxing enrichment can be applied with the following blockcode syntax

```json
Here goes your json object definition
```

Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.

How to find out the MySQL root password

you can view mysql root password , well i have tried it on mysql 5.5 so do not know about other new version well work or not

nano ~/.my.cnf

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

ConcurrentModificationException for ArrayList

Like the other answers say, you can't remove an item from a collection you're iterating over. You can get around this by explicitly using an Iterator and removing the item there.

Iterator<Item> iter = list.iterator();
while(iter.hasNext()) {
  Item blah = iter.next();
  if(...) {
    iter.remove(); // Removes the 'current' item
  }
}

Unable to set variables in bash script

folder = "ABC" tries to run a command named folder with arguments = and "ABC". The format of command in bash is:

command arguments separated with space

while assignment is done with:

variable=something

  • In [ -f $newfoldername/Primetime.eyetv], [ is a command (test) and -f and $newfoldername/Primetime.eyetv] are two arguments. It expects a third argument (]) which it can't find (arguments must be separated with space) and thus will show error.
  • [-f $newfoldername/Primetime.eyetv] tries to run a command [-f with argument $newfoldername/Primetime.eyetv]

Generally for cases like this, paste your code in shellcheck and see the feedback.

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

Import a file from a subdirectory?

I am writing this down because everyone seems to suggest that you have to create a lib directory.

You don't need to name your sub-directory lib. You can name it anything provided you put an __init__.py into it.

You can do that by entering the following command in a linux shell:

$ touch anything/__init__.py 

So now you have this structure:

$ ls anything/
__init__.py
mylib.py

$ ls
main.py

Then you can import mylib into main.py like this:

from anything import mylib 

mylib.myfun()

You can also import functions and classes like this:

from anything.mylib import MyClass
from anything.mylib import myfun

instance = MyClass()
result = myfun()

Any variable function or class you place inside __init__.py can also be accessed:

import anything

print(anything.myvar)

Or like this:

from anything import myvar

print(myvar)

How to Allow Remote Access to PostgreSQL database

After set listen_addresses = '*' in postgresql.conf

Edit the pg_hba.conf file and add the following entry at the very end of file:

host    all             all              0.0.0.0/0                       md5
host    all             all              ::/0                            md5

For finding the config files this link might help you.

Postgres FOR LOOP

Below is example you can use:

create temp table test2 (
  id1  numeric,
  id2  numeric,
  id3  numeric,
  id4  numeric,
  id5  numeric,
  id6  numeric,
  id7  numeric,
  id8  numeric,
  id9  numeric,
  id10 numeric) 
with (oids = false);

do
$do$
declare
     i int;
begin
for  i in 1..100000
loop
    insert into test2  values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;

Counting the number of option tags in a select tag in jQuery

$('#input1 option').length;

This will produce 2.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

This problem solved with

 "Origin, X-Requested-With, Content-Type, Accept, Authorization"

Particular in my project (express.js/nodejs)

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});

Update:

Every time error: Access-Control-Allow-Headers is not allowed by itself in preflight response error you can see what wrong with chrome developer tool:
enter image description here

above error is missing Content-Type so add string Content-Type to Access-Control-Allow-Headers

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate   = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.


The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00


Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.

For example in moment.js we would do moment1.diff(moment2, "seconds") which is beautiful.


Useful docs for this answer

How can I list all cookies for the current page with Javascript?

function listCookies() {
    let cookies = document.cookie.split(';')
    cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}

function findCookie(e) {
  let cookies = document.cookie.split(';')
  cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}

This is specifically for the window you're in. Tried to keep it clean and concise.

How to get enum value by string or int

Could be much simpler if you use TryParse or Parse and ToObject methods.

public static class EnumHelper
{
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val;
        return Enum.TryParse<T>(str, true, out val) ? val : default(T);
    }

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }

        return (T)Enum.ToObject(enumType, intValue);
    }
}

As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

How to make a WPF window be on top of all other windows of my app (not system wide)?

Just learning C# and ran across similar situation. but found a solution that I think may help. You may have figured this a long time ago. this will be from starting a new project but you can use it in any.

1) Start new project.

2) go to Project, then New Windows form, then select Windows Form and name Splash.

3) set size, background, text, etc as desired.

4) Under Properties of the Splash.cs form set Start Position: CenterScreen and TopMost: true

5) form1 add "using System.Threading;"

6) form1 under class add "Splash splashscreen = new Splash();"

7) form1 add "splashscreen.Show();" and "Application.DoEvents();"

8) form1 Under Events>>Focus>>Activated add "Thread.Sleep(4000); splashscreen.Close();"

9) Splash.cs add under "Public Splash" add "this.BackColor = Color.Aqua;" /can use any color

10) This is the code for Form1.cs

public partial class Form1 : Form
{
    Splash splashscreen = new Splash();
    public Form1()
    {
        InitializeComponent();
        splashscreen.Show();
        Application.DoEvents();

    }

    private void Form1_Activated(object sender, EventArgs e)
    {
        Thread.Sleep(4000);
        splashscreen.Close();
    }
}

11) this is the code on Splash.cs

public partial class Splash : Form
{
    public Splash()
    {
        InitializeComponent();
        this.BackColor = Color.Aqua;
    }
}

12) I found that if you do NOT do something in the splash then the screen will not stay on the top for the time the first form needs to activate. The Thread count will disappear the splash after x seconds, so your program is normal.

How to safely call an async method in C# without await

I'm late to the party here, but there's an awesome library I've been using which I haven't seen referenced in the other answers

https://github.com/brminnick/AsyncAwaitBestPractices

If you need to "Fire And Forget" you call the extension method on the task.

Passing the action onException to the call ensures that you get the best of both worlds - no need to await execution and slow your users down, whilst retaining the ability to handle the exception in a graceful manner.

In your example you would use it like this:

   public string GetStringData()
    {
        MyAsyncMethod().SafeFireAndForget(onException: (exception) =>
                    {
                      //DO STUFF WITH THE EXCEPTION                    
                    }); 
        return "hello world";
    }

It also gives awaitable AsyncCommands implementing ICommand out the box which is great for my MVVM Xamarin solution

What is the perfect counterpart in Python for "while not EOF"

You can imitate the C idiom in Python.

To read a buffer up to max_size number of bytes, you can do this:

with open(filename, 'rb') as f:
    while True:
        buf = f.read(max_size)
        if not buf:
            break
        process(buf)

Or, a text file line by line:

# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
    while True:
        line = f.readline()
        if not line:
            break
        process(line)

You need to use while True / break construct since there is no eof test in Python other than the lack of bytes returned from a read.

In C, you might have:

while ((ch != '\n') && (ch != EOF)) {
   // read the next ch and add to a buffer
   // ..
}

However, you cannot have this in Python:

 while (line = f.readline()):
     # syntax error

because assignments are not allowed in expressions in Python (although recent versions of Python can mimic this using assignment expressions, see below).

It is certainly more idiomatic in Python to do this:

# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
    for line in f:
        process(line)

Update: Since Python 3.8 you may also use assignment expressions:

 while line := f.readline():
     process(line)

Add key value pair to all objects in array

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});

console.log(arrOfObj);

When restoring a backup, how do I disconnect all active connections?

To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database

jQuery loop over JSON result from AJAX Success?

Try jQuery.map function, works pretty well with maps.

_x000D_
_x000D_
var mapArray = {_x000D_
  "lastName": "Last Name cannot be null!",_x000D_
  "email": "Email cannot be null!",_x000D_
  "firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
  alert("Value is :" + val);_x000D_
  alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

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

I added the start and exit which works. Without both it was not working

start C:/Anaconda3/Library/bin/pyrcc4.exe -py3 {path}/Resourses.qrc -{path}/Resourses_rc.py
exit

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

What does "implements" do on a class?

In Java a class can implement an interface. See http://en.wikipedia.org/wiki/Interface_(Java) for more details. Not sure about PHP.

Hope this helps.

Can you delete multiple branches in one command with Git?

I just cleaned up a large set of obsolete local/remote branches today.

Below is how I did it:

1. list all branch names to a text file:

git branch -a >> BranchNames.txt

2. append the branches I want to delete to command "git branch -D -r":

git branch -D -r origin/dirA/branch01 origin/dirB/branch02 origin/dirC/branch03 (... append whatever branch names)

3. execute the cmd

And this one works so much faster and reliable than "git push origin --delete".

This may not be the most smart way as listed in other answers, but this one is pretty straight forward, and easy to use.

android : Error converting byte to dex

Check you build.gradle (Module: your app).

All com.google.android.gms libraries must use the exact same version specification (mixing versions can lead to runtime crashes).

For example: If you have com.google.firebase:firebase-ads:9.6.1 and com.google.android.gms:play-services-basement:10.0.1

You have to change the firebase version to: 10.0.1

At least one JAR was scanned for TLDs yet contained no TLDs

For anyone trying to get this working using the Sysdeo Eclipse Tomcat plugin, try the following steps (I used Sysdeo Tomcat Plugin 3.3.0, Eclipse Kepler, and Tomcat 7.0.53 to construct these steps):

  1. Window --> Preferences --> Expand the Tomcat node in the tree --> JVM Settings
  2. Under "Append to JVM Parameters", click the "Add" button.
  3. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.config.file="{TOMCAT_HOME}\conf\logging.properties", where {TOMCAT_HOME} is the path to your Tomcat directory (example: C:\Tomcat\apache-tomcat-7.0.53\conf\logging.properties). Click OK.
  4. Under "Append to JVM Parameters", click the "Add" button again.
  5. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager. Click OK.
  6. Click OK in the Preferences window.
  7. Make the adjustments to the {TOMCAT_HOME}\conf\logging.properties file as specified in the question above.
  8. The next time you start Tomcat in Eclipse, you should see the scanned .jars listed in the Eclipse Console instead of the "Enable debug logging for this logger" message. The information should also be logged in {TOMCAT_HOME}\logs\catalina.yyyy-mm-dd.log.

"Items collection must be empty before using ItemsSource."

The reason this particular exception gets thrown is that the content of the element gets applied to the ListView's Items collection. So the XAML initialises the ListView with a single local:ImageView in its Items collection. But when using an ItemsControl you must use either the Items property or the ItemsSource property, you can't use both at the same time. Hence when the ItemsSource attribute gets processed an exception is thrown.

You can find out which property the content of an element will get applied to by looking for the ContentPropertyAttribute on the class. In this case it's defined higher in the class hierarchy, on the ItemsControl:

[ContentPropertyAttribute("Items")]

The intention here was that the ListView's View be set to a local:ImageView so the fix is to explicitly indicate the property to be set.

Fix the XAML and the exception goes away:

<ListView Name="ListViewImages"
          SelectionMode="Single"
          ItemsSource="{Binding}">
    <ListView.View>
        <local:ImageView />
    </ListView.View>
</ListView>

It was missing that <ListView.View> tag.

How can I store the result of a system command in a Perl variable?

From Perlfaq8:

You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.

$exit_status   = system("mail-users");
$output_string = `ls`;

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don't want to capture its output
  • exec: you don't want to return to the calling perl script
  • backticks : you want to capture the output of the command
  • open: you want to pipe the command (as input or output) to your script

Also see How can I capture STDERR from an external command?

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

There is probably another table with a foreign key referencing the primary key you are trying to change.

To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section.

Functions that return a function

This is super useful in real life.

Working with Express.js

So your regular express route looks like this:

function itWorksHandler( req, res, next ) {
  res.send("It works!");
}

router.get("/check/works", itWorksHandler );

But what if you need to add some wrapper, error handler or smth?

Then you invoke your function off a wrapper.

function loggingWrapper( req, res, next, yourFunction ) {
  try {
    yourFunction( req, res );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", function( req, res, next ) {
  loggingWrapper( req, res, next, itWorksHandler );
});

Looks complicated? Well, how about this:

function function loggingWrapper( yourFunction ) => ( req, res, next ) {
  try {
    yourFunction( req, res, next );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", loggingWrapper( itWorksHandler ) );

See at the end you're passing a function loggingWrapper having one argument as another function itWorksHandler, and your loggingWrapper returns a new function which takes req, res, next as arguments.

Set environment variables from file of key/value pairs

Problem with your approach is the export in the while loop is happening in a sub shell, and those variable will not be available in current shell (parent shell of while loop).

Add export command in the file itself:

export MINIENTREGA_FECHALIMITE="2011-03-31"
export MINIENTREGA_FICHEROS="informe.txt programa.c"
export MINIENTREGA_DESTINO="./destino/entrega-prac1"

Then you need to source in the file in current shell using:

. ./conf/prac1

OR

source ./conf/prac1

How to create a GUID/UUID using iOS

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

EDIT: -[UIDevice uniqueIdentifier] is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.

If you need to create several UUID, just use this method (with ARC):

+ (NSString *)GetUUID
{
  CFUUIDRef theUUID = CFUUIDCreate(NULL);
  CFStringRef string = CFUUIDCreateString(NULL, theUUID);
  CFRelease(theUUID);
  return (__bridge NSString *)string;
}

EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:

NSString *UUID = [[NSUUID UUID] UUIDString];

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

How do you specify a different port number in SQL Management Studio?

127.0.0.1,6283

Add a comma between the ip and port

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Fast way of finding lines in one file that are not in another?

Use combine from moreutils package, a sets utility that supports not, and, or, xor operations

combine file1 not file2

i.e give me lines that are in file1 but not in file2

OR give me lines in file1 minus lines in file2

Note: combine sorts and finds unique lines in both files before performing any operation but diff does not. So you might find differences between output of diff and combine.

So in effect you are saying

Find distinct lines in file1 and file2 and then give me lines in file1 minus lines in file2

In my experience, it's much faster than other options

C# 4.0 optional out/ref arguments

As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:

Formal parameters of constructors, methods, indexers and delegate types can be declared optional:

fixed-parameter:
    attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
    = expression

  • A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
  • A required parameter cannot appear after an optional parameter in a formal-parameter-list.
  • A ref or out parameter cannot have a default-argument.

Extending from two classes

You will want to use interfaces. Generally, multiple inheritance is bad because of the Diamond Problem:

abstract class A {
 abstract string foo();
}

class B extends A {
 string foo () { return "bar"; }
}

class C extends A  {
 string foo() {return "baz"; }
}

class D extends B, C {
 string foo() { return super.foo(); } //What do I do? Which method should I call?
}

C++ and others have a couple ways to solve this, eg

string foo() { return B::foo(); }

but Java only uses interfaces.

The Java Trails have a great introduction on interfaces: http://download.oracle.com/javase/tutorial/java/concepts/interface.html You'll probably want to follow that before diving into the nuances in the Android API.

string sanitizer for filename

preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)

Add/remove more valid characters depending on what is allowed for your system.

Alternatively you can try to create the file and then return an error if it's bad.

Abstract methods in Python

Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).

Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.

def abstractmethod(method):
    """
    An @abstractmethod member fn decorator.
    (put this in some library somewhere for reuse).

    """
    def default_abstract_method(*args, **kwargs):
        raise NotImplementedError('call to abstract method ' 
                                  + repr(method))
    default_abstract_method.__name__ = method.__name__    
    return default_abstract_method


class Shape(object):

    def __init__(self, shape_name):
       self.shape = shape_name

    @abstractmethod
    def foo(self):
        print "bar"
        return

class Rectangle(Shape):
    # note you don't need to do the constructor twice either
    pass  

r = Rectangle("x")
r.foo()

I didn't write the decorator. It just occurred to me someone would have. You can find it here: http://code.activestate.com/recipes/577666-abstract-method-decorator/ Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).

Regex, every non-alphanumeric character except white space or colon

If you want to treat accented latin characters (eg. à Ñ) as normal letters (ie. avoid matching them too), you'll also need to include the appropriate Unicode range (\u00C0-\u00FF) in your regex, so it would look like this:

/[^a-zA-Z\d\s:\u00C0-\u00FF]/g
  • ^ negates what follows
  • a-zA-Z matches upper and lower case letters
  • \d matches digits
  • \s matches white space (if you only want to match spaces, replace this with a space)
  • : matches a colon
  • \u00C0-\u00FF matches the Unicode range for accented latin characters.

nb. Unicode range matching might not work for all regex engines, but the above certainly works in Javascript (as seen in this pen on Codepen).

nb2. If you're not bothered about matching underscores, you could replace a-zA-Z\d with \w, which matches letters, digits, and underscores.

Changing the maximum length of a varchar column?

This worked for me in db2:

alter table "JOBS"  alter column "JOB_TITLE" set  data type varchar(30);

Can I use Class.newInstance() with constructor arguments?

MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");

or

obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");

Pie chart with jQuery

There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:

https://zoomcharts.com/

Example of charts:

interactive pie chart

Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/

What is cool about this lib:

  • Others slice can be expanded
  • Pie offers drill down for hierarchical structures (see example)
  • write your own data source controller easily, or provide simple json file
  • export high res images out of box
  • full touch support, works smoothly on iPad, iPhone, android, etc.

enter image description here

Charts are free for non-commercial use, commercial licenses and technical support available as well.

Also interactive Time charts and Net Charts are there for you to use. enter image description here

enter image description here

Charts come with extensive API and Settings, so you can control every aspect of the charts.

How to import the class within the same directory or sub directory?

Python 3


Same directory.

import file:log.py

import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

directory is basic.

import in file: log.py.

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

How to check if element exists using a lambda expression?

The above answers require you to malloc a new stream object.

public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {

    for (final T z : c) {
        if (p.test(z)) {
            return true;
        }
    }
    return false;
}

public boolean containsTabById(TabPane tabPane, String id) {
    return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
   ...
}

Blank HTML SELECT without blank item in dropdown list

You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.

You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.

How to implement WiX installer upgrade?

The Upgrade element inside the Product element, combined with proper scheduling of the action will perform the uninstall you're after. Be sure to list the upgrade codes of all the products you want to remove.

<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="00000000-0000-0000-0000-000000000000">
  <UpgradeVersion Minimum="1.0.0.0" Maximum="1.0.5.0" Property="PREVIOUSVERSIONSINSTALLED" IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>

Note that, if you're careful with your builds, you can prevent people from accidentally installing an older version of your product over a newer one. That's what the Maximum field is for. When we build installers, we set UpgradeVersion Maximum to the version being built, but IncludeMaximum="no" to prevent this scenario.

You have choices regarding the scheduling of RemoveExistingProducts. I prefer scheduling it after InstallFinalize (rather than after InstallInitialize as others have recommended):

<InstallExecuteSequence>
  <RemoveExistingProducts After="InstallFinalize"></RemoveExistingProducts>
</InstallExecuteSequence>

This leaves the previous version of the product installed until after the new files and registry keys are copied. This lets me migrate data from the old version to the new (for example, you've switched storage of user preferences from the registry to an XML file, but you want to be polite and migrate their settings). This migration is done in a deferred custom action just before InstallFinalize.

Another benefit is efficiency: if there are unchanged files, Windows Installer doesn't bother copying them again when you schedule after InstallFinalize. If you schedule after InstallInitialize, the previous version is completely removed first, and then the new version is installed. This results in unnecessary deletion and recopying of files.

For other scheduling options, see the RemoveExistingProducts help topic in MSDN. This week, the link is: http://msdn.microsoft.com/en-us/library/aa371197.aspx

How to split a string with any whitespace chars as delimiters

All you need is to split using the one of the special character of Java Ragex Engine,

and that is- WhiteSpace Character

  • \d Represents a digit: [0-9]
  • \D Represents a non-digit: [^0-9]
  • \s Represents a whitespace character including [ \t\n\x0B\f\r]
  • \S Represents a non-whitespace character as [^\s]
  • \v Represents a vertical whitespace character as [\n\x0B\f\r\x85\u2028\u2029]
  • \V Represents a non-vertical whitespace character as [^\v]
  • \w Represents a word character as [a-zA-Z_0-9]
  • \W Represents a non-word character as [^\w]

Here, the key point to remember is that the small leter character \s represents all types of white spaces including a single space [ ] , tab characters [ ] or anything similar.

So, if you'll try will something like this-

String theString = "Java<a space><a tab>Programming"
String []allParts = theString.split("\\s+");

You will get the desired output.


Some Very Useful Links:


Hope, this might help you the best!!!

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

How to configure XAMPP to send mail from localhost?

in addition to all answers please note that in sendmail.ini file:

auth_password=this-is-Not-your-Gmail-password

due to new google security concern, you should follow these steps to make an application password for this purpose:

  1. go to https://accounts.google.com/ in security tab
  2. turn two-step-verification on
  3. go back to the security tab and make an App-password (in select-app drop-down menu you can choose 'other')

Entity Framework Query for inner join

You could use a navigation property if its available. It produces an inner join in the SQL.

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s

Convert JS object to JSON string

For debugging in Node JS you can use util.inspect(). It works better with circular references.

var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));

Is there an ignore command for git like there is for svn?

You could also use Joe Blau's gitignore.io

Either through the web interfase https://www.gitignore.io/

Or by installing the CLI tool, it's very easy an fast, just type the following on your terminal:

Linux:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bashrc && source ~/.bashrc

OSX:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bash_profile && source ~/.bash_profile

And then you can just type gi followd by the all the platform/environment elements you need gitignore criteria for.

Example!
Lets say you're working on a node project that includes grunt and you're using webstorm on linux, then you may want to type:
gi linux,webstorm,node,grunt > .gitignore ( to make a brand new file)
or
gi linux,webstorm,node,grunt >> .gitignore ( to append/add the new rules to an existing file)

bam, you're good to go

Sorting arrays in javascript by object key value

Here's the same as the current top answer, but in an ES6 one-liner:

myArray.sort((a, b) => a.distance - b.distance);

bash, extract string before a colon

Another pure BASH way:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv

Can a foreign key refer to a primary key in the same table?

Eg: n sub-category level for categories .Below table primary-key id is referred by foreign-key sub_category_id

enter image description here

Cache an HTTP 'Get' service response in AngularJS?

Angular's $http has a cache built in. According to the docs:

cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.

Boolean value

So you can set cache to true in its options:

$http.get(url, { cache: true}).success(...);

or, if you prefer the config type of call:

$http({ cache: true, url: url, method: 'GET'}).success(...);

Cache Object

You can also use a cache factory:

var cache = $cacheFactory('myCache');

$http.get(url, { cache: cache })

You can implement it yourself using $cacheFactory (especially handly when using $resource):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);
   });
}